0

is there a way to swap the first and second elements for all tuples in a vector? Let's say I have something like this:

#include<vector>
#include<tuple>

int main()
{
std::vector<std::tuple<int,int>> my_vector;
my_vector.push_back(std::make_tuple(1,2));
my_vector.push_back(std::make_tuple(3,4));
}

The first elements of the tuple are now 1 and 3 with the second elements being 2 and 4. Is there an easy to make 2 and 4 the first elements?

AkariYukari
  • 338
  • 4
  • 16

2 Answers2

6

You can use std::for_each algorithm with a lambda:

std::for_each(my_vector.begin(), my_vector.end(), [](auto& tuple) {
    std::swap(std::get<0>(tuple), std::get<1>(tuple));
});

You can also use a range-based for:

for (auto& tuple : my_vector)
    std::swap(std::get<0>(tuple), std::get<1>(tuple));

If you decide to replace std::tuple with std::pair, this code will also work, because std::pair's members first and second can be accessed using std::get<0> and std::get<1>, respectively.


Instead of std::swap(...) you might want to write it this way:

using std::swap;
swap(std::get<0>(tuple), std::get<1>(tuple));

This is useful if instead of int, you have some user-defined type T, for which void swap(T&, T&) function is implemented (being presumably more performant than std::swap) and can be found by argument-dependent lookup.

Evg
  • 25,259
  • 5
  • 41
  • 83
2

Since your std::tuples are containing only two values, I would suggest using std::pair instead.

#include <iostream>
#include <vector>
#include <utility>

int main()
{
    std::vector<std::pair<int,int>> my_vector;
    my_vector.push_back(std::make_pair(1,2));
    my_vector.push_back(std::make_pair(3,4));

    for (auto const& p : my_vector) {
        std::cout << p.first << " " << p.second << std::endl;
    }

    for (auto& p : my_vector) {
        std::swap(p.first, p.second);
    }

    for (auto const& p : my_vector) {
        std::cout << p.first << " " << p.second << std::endl;
    }
}

Live example

NutCracker
  • 11,485
  • 4
  • 44
  • 68