I have a vector of integers:
std::vector values = {1,2,3,4,5,6,7,8,9,10};
Given that values.size() will always be even.
I simply want to convert the adjacent elements into a pair, like this:
std::vector<std::pair<int,int>> values = { {1,2}, {3,4} , {5,6}, {7,8} ,{9,10} };
I.e., the two adjacent elements are joined into a pair.
What STL algorithm can I use to easily achieve this? Is it possible to achieve this through some standard algorithms?
Of course, I can easily write an old-school indexed for loop to achieve that. But I want to know what the simplest solution could look like using range-based for loops or any other STL algorithm, like std::transform, etc.
Answer 1
Once we have C++23’s extension to , you can get most of the way there with std::ranges::views::chunk, although that produces subranges, not pairs.
#include #include #include </code> int main() { std::vector values = {1,2,3,4,5,6,7,8,9,10}; auto chunk_to_pair = [](auto chunk) { return std::pair(*chunk.begin(), *std::next(chunk.begin())); }; for (auto [first, second] : values | std::ranges::views::chunk(2) | std::ranges::views::transform(chunk_to_pair)) { std::cout << first << second << std::endl; } }
Alternatively, you could achieve a similar result by ziping a pair of strided views
#include #include #include int main() { std::vector values = {1,2,3,4,5,6,7,8,9,10}; auto odds = values | std::ranges::views::drop(0) | std::ranges::views::stride(2); auto evens = values | std::ranges::views::drop(1) | std::ranges::views::stride(2); for (auto [first, second] : std::ranges::views::zip(odds, evens)) { std::cout << first << second << std::endl; } }