交换向量中的两个值
Swap two values in a vector
我试图在一组随机点的图形上找到最左边的点。例如,在点 (3, 5) (5, 2) (8, 7) (1, 3) 中,最左边的点是 (1, 3)。执行此操作后,我必须将最左边的点放在向量的点 0 中。我无法切换两个变量,因为我不知道 mostLeft 最初来自哪个点。
mostLeft 是一个包含两个整数的节点。
我试过使用
swap(list[0], mostLeft)
但它只是复制了 mostLeft 两次。
我也试过了
Point temp = list[0];
list.erase(remove(list.begin(), list.end(). mostLeft), list.end());
list[0] = left;
list.push_back(temp);
但这给了我错误 "cannot convert vector to const char* for argument to remove"。我从网上得到了第二块代码。我不确定它是如何工作的,但我一直看到它弹出,所以我试了一下。
是否有一种简单的方法来交换这些值,或者我必须手动遍历向量并找到值。
如果我没有正确理解你想要实现的目标,那么你可以使用以下方法
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::pair<int, int>> v =
{
{ 3, 5 }, { 5, 2 }, { 8, 7 }, { 1, 3 }
};
for (const auto &p : v)
{
std::cout << "(" << p.first << ", " << p.second << ") ";
}
std::cout << std::endl;
auto mostLeft = [](const auto &a, const auto &b) { return a.first < b.first; };
std::swap(v[0], *std::min_element(v.begin(), v.end(), mostLeft));
for (const auto &p : v)
{
std::cout << "(" << p.first << ", " << p.second << ") ";
}
std::cout << std::endl;
}
程序输出为
(3, 5) (5, 2) (8, 7) (1, 3)
(1, 3) (5, 2) (8, 7) (3, 5)
我试图在一组随机点的图形上找到最左边的点。例如,在点 (3, 5) (5, 2) (8, 7) (1, 3) 中,最左边的点是 (1, 3)。执行此操作后,我必须将最左边的点放在向量的点 0 中。我无法切换两个变量,因为我不知道 mostLeft 最初来自哪个点。 mostLeft 是一个包含两个整数的节点。
我试过使用
swap(list[0], mostLeft)
但它只是复制了 mostLeft 两次。
我也试过了
Point temp = list[0];
list.erase(remove(list.begin(), list.end(). mostLeft), list.end());
list[0] = left;
list.push_back(temp);
但这给了我错误 "cannot convert vector to const char* for argument to remove"。我从网上得到了第二块代码。我不确定它是如何工作的,但我一直看到它弹出,所以我试了一下。
是否有一种简单的方法来交换这些值,或者我必须手动遍历向量并找到值。
如果我没有正确理解你想要实现的目标,那么你可以使用以下方法
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::pair<int, int>> v =
{
{ 3, 5 }, { 5, 2 }, { 8, 7 }, { 1, 3 }
};
for (const auto &p : v)
{
std::cout << "(" << p.first << ", " << p.second << ") ";
}
std::cout << std::endl;
auto mostLeft = [](const auto &a, const auto &b) { return a.first < b.first; };
std::swap(v[0], *std::min_element(v.begin(), v.end(), mostLeft));
for (const auto &p : v)
{
std::cout << "(" << p.first << ", " << p.second << ") ";
}
std::cout << std::endl;
}
程序输出为
(3, 5) (5, 2) (8, 7) (1, 3)
(1, 3) (5, 2) (8, 7) (3, 5)