Use CMake to build and run cross-platform (WIN32 and LINUX) code. (Part 1)

CMake is a build configuration tool. In other words, CMake generates Makefiles. This post gives an example on how to configure CMake (the actual content of CMakeLists.txt) to build and run C++ code in Windows as well as in Linux. Here it goes:

cmake_minimum_required(VERSION 3.22.1)

# Enable Hot Reload for MSVC compilers if supported.
if (POLICY CMP0141)
  cmake_policy(SET CMP0141 NEW)
  set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<IF:$<AND:$<C_COMPILER_ID:MSVC>,$<CXX_COMPILER_ID:MSVC>>,$<$<CONFIG:Debug,RelWithDebInfo>:EditAndContinue>,$<$<CONFIG:Debug,RelWithDebInfo>:ProgramDatabase>>")
endif()

message(STATUS "Checking target system...")

if(WIN32 OR MSVC)
   message(STATUS "Target system is Windows")
   set(BOOST_ROOT <Path to your boost directory in Windows>)
   set(Boost_INCLUDE_DIR ${BOOST_DIR})
endif()

if(UNIX)
   message(STATUS "Target system is Linux")
   set(BOOST_ROOT <Path to your boost directory in Linux>)
endif()

set(Boost_USE_STATIC_LIBS_ON)
find_package(Boost REQUIRED)
include_directories(${Boost_INCLUDE_DIR})

project(<Project name>)
add_executable(<Project name>
    main.cc
)
target_compile_features(<Project name>PUBLIC cxx_std_20)
target_link_libraries(<Project name> ${Boost_SYSTEM_LIBRARY})

The example above links only the headers and not the binaries. How to link binaries will come in the next part.

[codeforces]230A DRAGONS – Sort with custom comparator

Problem statement is here: http://codeforces.com/contest/230/problem/A

The problem is not difficult, what makes it even easier it that even O(n^2) solution is accepted by the judge.

If you consider each Dragon as a struct of strength that it possesses and the bonus it gives then the problem becomes a matter of sorting Dragons that can be killed by the player’s initial strength. I have sorted using a custom comparator which makes life a lot easy. Here is the code:

#include <bits/stdc++.h>

struct Dragon {
  int strength;
  int bonus;
  Dragon(int strength, int bonus) : strength(strength), bonus(bonus) {}
};

bool comparator(Dragon i, Dragon j) {
  return i.strength < j.strength;
}

int main() {
  int player_strength;
  int num_dragons;

  std::cin >> player_strength >> num_dragons;

  std::vector<Dragon> dragons;

  for (int i = 0; i < num_dragons; i++) {
    int strength, bonus;
    std::cin >> strength >> bonus;
    dragons.push_back(Dragon(strength, bonus));
  }

  std::sort(dragons.begin(), dragons.end(), comparator);

  for(Dragon dragon : dragons) {
    if(dragon.strength < player_strength) {
      player_strength+=dragon.bonus;
    }
    else {
      std::cout<<"NO";
      return 0;
    }
  }

  std::cout<<"YES";

  return 0;
}

Please let me know in comments if you have found a more optimal way to solve the problem. Cheers!