2022-11-20

# C++23 AlgorithmsC++23 AlgorithmsC++23 Algorithms

The algorithms below will be part of the C++23 standard library. They are now listed on the range algorithms overview page in the Beginner's Guide sections and on the Cheat Sheets page.

Note that it might take a few months until the example programs will run in Compiler Explorer as most of these new algorithms are not available in any standard library implementation yet.

std::vector<int> v {2,1,7,1,1,5,8};
auto const result = std::ranges::find_last(v, 1);
if (not result.empty()) {   // if found
auto const value = result.front();  // int value = 1
auto const index = distance(begin(v),begin(result));  // index = 4
}
for (int x : result) { cout << x << ' '; }  // 1 5 8

std::vector<int> v {4,1,3,8,1};
auto const f = [](int x) {   return x >= 2; };
auto const result = std::ranges::find_last_if (v, f);
if (not result.empty()) {   // if found
auto const value = result.front();  // int value = 8
auto const index = distance(begin(v),begin(result));  // index = 3
}
for (int x : result) { cout << x << ' '; }  // 8 1

std::vector<int> v {4,0,3,1,5};
auto const f = [](int x) {   return x >= 2; };
auto const result = std::ranges::find_last_if_not(v, f);
if (not result.empty()) {   // if found
auto const value = result.front();  // int value = 1
auto const index = distance(begin(v),begin(result));  // index = 3
}
for (int x : result) { cout << x << ' '; }  // 1 5

std::vector<int> s {4,6,5,8,7,3};
std::vector<int> w {4,6,5};
if (std::ranges::starts_with(sw) ) {
cout << "yes!\n";
}

std::vector<int> s {4,6,5,8,7,3};
std::vector<int> w {8,7,3};
if (std::ranges::ends_with(sw) ) {
cout << "yes!\n";
}

std::vector<int> v {1,2,3,4,5,6,7,8};
int const by = 3;
auto result = ranges::shift_left(v, by);
for (int x : result) { cout << x <<' '; }  // 4 5 6 7 8

std::vector<int> v {1,2,3,4,5,6,7,8};
int const by = 3;
auto result = ranges::shift_right(v, by);
for (int x : result) { cout << x <<' '; }  // 1 2 3 4 5

std::vector<int> v;
v.resize(5,0);
auto const res = ranges::iota(v, 3);
std::cout << res.value;  // 8
for (int x : v) { cout << x << ' '; }  // 3 4 5 6 7