기타

C++ 몰랐던 것들.. (1)

카멜레온개발자 2021. 11. 4. 14:29

1. 변수의 최대 최소값 구하기

#include <algorithm>


int val1 = -10;
int val2 = -5;
std::cout << std::min(val1, val2) << std::endl;

/*기본적으로 < 순서인데, 양쪽에 절대값이므로 절대값 기준의 최대 최소를 가져온다*/
std::cout << std::min(-10, -5, [](int a, int b) {
    return std::abs(a) < std::abs(b);
}) << std::endl;

auto pairInt = std::minmax(201, 202);
std::cout << "Min : " << pairInt.first << std::endl;
std::cout << "Max : " << pairInt.second << std::endl;

auto pairSeq = std::minmax({ 2,3,43,5,6,7 });
std::cout << "Min : " << pairSeq.first << std::endl;
std::cout << "Max : " << pairSeq.second << std::endl;

2. 배열에서 최대/최소값 구하기

#include <algorithm>

//std::begin, std::end를 이용
int arr[3] = { 1,2,3 };
auto res_min = std::min_element(arr, arr + 3);
auto res_max = std::max_element(arr, arr + 3);
auto res_min2 = std::min_element(std::begin(arr), std::end(arr));
auto res_max2 = std::max_element(std::begin(arr), std::end(arr));

3. vector의 이동

//1000000개의 vector, 각 항목은 1
std::vector<int> srcVec(1000000, 1);

//vector의 복사가 이루어진다
std::vector<int> dstVec  = srcVec;
//srcVec을 잘라내서 dstVec2에 붙여 넣는다
std::vector<int> dstVec2 = std::move(srcVec);

4. std::funcion, std::bind

    std::function<double(double, double)> mDiv1 = std::bind(diveMe, std::placeholders::_1, std::placeholders::_2);
    std::function<double(double)>         mDiv2 = std::bind(diveMe, 20000, std::placeholders::_1);

    double mDiv1_Result = mDiv1(1, 2);
    double mDiv2_Result = mDiv2(2);

    std::map<const char, std::function<double(double, double)>> tab;
    tab.insert(std::make_pair('+', [](double a, double b) {return a + b; }));
    tab.insert(std::make_pair('-', [](double a, double b) {return a - b; }));
    tab.insert(std::make_pair('*', [](double a, double b) {return a * b; }));
    tab.insert(std::make_pair('/', [](double a, double b) {return a / b; }));

    std::cout << " 3 + 5 : " << tab['+'](3, 5) << std::endl;
    std::cout << " 3 - 5 : " << tab['-'](3, 5) << std::endl;
    std::cout << " 3 * 5 : " << tab['*'](3, 5) << std::endl;
    std::cout << " 3 / 5 : " << tab['/'](3, 5) << std::endl;