c++:交换向量中所有元组的第一个和第二个元素

c++: Swap first and second element for all tuples in a vector

本文关键字:第一个 第二个 元素 元组 交换 向量 c++      更新时间:2023-10-16

有没有办法交换向量中所有元组的第一个和第二个元素? 假设我有这样的东西:

#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));
}

元组的第一个元素现在是 1 和 3,第二个元素是 2 和 4。有没有一个容易使 2 和 4 成为第一个元素?

您可以将std::for_each算法与lambda一起使用:

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

您还可以使用基于范围的for

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

如果你决定用std::pair替换std::tuple,这段代码也可以工作,因为std::pair的成员firstsecond可以分别使用std::get<0>std::get<1>进行访问。


与其std::swap(...),不如这样写:

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

这很有用,而不是int,你有一些用户定义的类型Tvoid swap(T&, T&)函数被实现(可能比std::swap更高性能(,并且可以通过依赖于参数的查找找到。

由于您的std::tuple只包含两个值,因此我建议改用std::pair

#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;
}
}

现场示例

相关文章: