【问题标题】:Swap two values in a vector [closed]交换向量中的两个值[关闭]
【发布时间】:2017-10-12 22:52:32
【问题描述】:

我试图在一组随机点的图表上找到最左边的点。例如,在点 (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);

但这给了我错误“无法将向量转换为 const char* 以删除参数”。我从网上得到了第二个代码块。我不确定它是如何工作的,但我一直看到它弹出,所以我试了一下。

有没有一种简单的方法可以交换这些值,或者我必须手动遍历向量并找到值。

【问题讨论】:

  • 请提供一个有效的最小示例,该代码既不能编译,bein()list.end().mostleft 肯定不是取自您正在使用或尝试使用的东西。
  • @mhemmy 目前还不清楚你是如何在 swap(list[0], mostLeft) 中得到 mostLeft 的
  • 我猜mostLeft 不是参考。
  • 我的意思是 list.begin()。
  • 如果您引用错误,请引用整个内容,包括编译器肯定给您的行号/列号

标签: c++ algorithm vector swap


【解决方案1】:

如果我正确理解了您要达到的目标,那么您可以使用以下方法

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多