【问题标题】:Sort a vector with another vector using lambda function [duplicate]使用 lambda 函数对一个向量与另一个向量进行排序
【发布时间】:2017-12-06 14:57:36
【问题描述】:

在下面的代码中,出现分段错误。我认为问题出在索引上,但我不明白为什么。是否可以使用std::sort 和 lambda 函数根据另一个向量对一个向量进行排序?

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>

int main()
{
    std::vector<std::string> A = {"b", "a", "c"};
    std::vector<int> B = {2, 1, 3};

    std::sort(std::begin(A), std::end(A),
            [&](const std::string& t1, const std::string& t2)
            {
            return B[&t1-A.data()] > B[&t2-A.data()]; // problem could be here!
            });

    std::cout << A[0] << std::endl;
    std::cout << A[1] << std::endl;
    std::cout << A[2] << std::endl;

    return 0;
}

【问题讨论】:

  • &amp;t1-A.data() 看起来不应该用于索引向量
  • 你知道&amp;t1是内存地址吗?
  • @tobi303 找到元素 t1 是有意义的。
  • 你没有考虑到元素在排序过程中可以移动。
  • 真正的目标是什么?是否将索引向量排序到A 向量中,而不必实际对A 向量进行排序?如果是这样,则方法不正确。

标签: c++ sorting c++11 vector lambda


【解决方案1】:

而不是按照自己的方式获取索引是一种简单的方式。

std::sort(std::begin(A), std::end(A),
        [&](const std::string& t1, const std::string& t2)
        {
          int index1, index2;
          for(int i = 0; i<A.size(); i++) {
            if(&A[i] == &t1) index1 = i;
            if(&A[i] == &t2) index2 = i;
          }
        return B[index1] > B[index2];
        });

这种方式是安全的,并确保它获得正确的索引。测试后输出为C \n B \n A,这是我认为你想要的。

希望这会有所帮助。

【讨论】:

  • 此方法将排序运行时间增加到O(n^2 logn)
  • @AlbinPaul 我不认为运行时是一个问题,但我会优化它。
  • 这看起来像是将 std::sort 从对数时间复杂度转换为 O(n^2) 时间复杂度。想象一下如果A 有 1000 个元素。
  • 我想知道为什么我的方法失败了。
  • 仅供参考,不同情况下的输出不正确。例如,b a c3 2 1 gives me 的输入与 GCC 的 b c a 输出。添加-O2 会导致段错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 2023-04-04
  • 2012-07-05
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多