【问题标题】:sorting iterators with std::sort使用 std::sort 对迭代器进行排序
【发布时间】:2016-12-31 20:39:28
【问题描述】:

我想对包含指向另一个向量 int_vec 中的元素的 int 迭代器的向量 vec 进行排序。我想使用以下比较功能:it1

index[it1 - int_vec.begin()] < index[it2 - int_vec.begin()]. 

其中 index 是指定迭代器键的第三个向量。现在向量索引是 A 的构造函数的内部数组,而 int_vec 是类 A 的成员变量。我试图像这样传递一个匿名函数:

std::sort(vec.begin(),flow.end(), [&index,&edges](const int_iter it1 ,const int_iter it2) -> bool
{ 
    index[it1 - int_vec.begin()] < index[it2 - int_vec.begin()]; 
})

但我收到一条错误消息,告诉我无法捕获成员对象。确切的错误信息是:

'this' cannot be implicitly captured in this context
        index[it1 - int_vec.begin()] < index[it2 - int_vec.begin()];.

我也试图只声明一个外部比较函数,但我不清楚如何将两个固定值绑定到它(我读到了 boost::bind 看起来正好解决了这个问题,但我宁愿不下载附加库)。

【问题讨论】:

  • 我想对包含 int 迭代器的向量 vec 进行排序,该迭代器指向另一个向量 int_vec 中的元素 -- 仅此一项是个坏主意,因为如果向量已调整大小。
  • 但向量永远不会调整大小
  • 那为什么是向量呢?使用std::array
  • '成员对象不能被捕获',听起来你需要捕获这个,[this]
  • 请在您的问题中添加确切的错误消息。

标签: c++ sorting


【解决方案1】:

你有很多问题。

  1. 最明显的就是你的代码缺少[this]

  2. vec.begin(),flow.end()

你不能取一个向量的开头和另一个向量的结尾。

这是更正后的代码:

std::sort(vec.begin(),vec.end(), [this,&index,&edges](const int_iter it1 ,const int_iter it2) -> bool
{ 
    index[it1 - int_vec.begin()] < index[it2 - int_vec.begin()]; 
})

但是,您应该告诉我们您想要达到的目标,我相信我们可以找到更好的解决方案。使用其他向量的迭代器的向量已经很危险了,不检查就对它们做减法是粗心的。

危险性较小的解决方案:

std::vector<int> int_vec;
std::vector<size_t> int_vec_order(int_vec.size());
std::iota(int_vec_order.begin(), int_vec_order.end(), size_t(0));

std::sort(int_vec_order.begin(), int_vec_order.end(), [&int_vec](const size_t a, const size_t b) {
  // apply your order to int_vec.at(a) and int_vec.at(b)
});

// output them
for(const size_t i : int_vec_order) {
  // output int_vec.at(i)
}

【讨论】:

  • 哦,流程是一个错字。所以这有点编造。实际上 int_vec 不存储 int 而是非常大的结构,我不想复制它们,所以这就是我使用迭代器的原因。也许这样说会更好。我想做以下事情:我将一些按预定义顺序获得的对象存储在 int_vec 中,然后在其中存储一些其他对象。然后我对 int_vec 进行排序(按一些不重要的顺序)。现在我想按预定义的顺序打印对象(但不是 int_vec 中的其他对象)。
  • 编辑了答案。您始终可以使用危险性较小的索引。
  • @user3726947 解决方案是使用索引,而不是迭代器。 See this answer
  • 这不正是我写的吗?
  • 您的编辑没有准确显示如何编写排序的 lambda 部分。
猜你喜欢
  • 1970-01-01
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多