用std ::排序迭代器

sorting iterators with std::sort

本文关键字:迭代器 排序 std      更新时间:2023-10-16

我想对含有int迭代器的向量vec进行指向另一个vector int_vec中的元素。我想使用以下比较函数:it1<IT2时,仅当

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

索引是第三个向量,指定迭代器的键。现在,向量索引是A和INT_VEC的构造函数的内部数组。

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 bind,bind bind bind bind bind bind bind bind bind bind bind bind bind bind of cockity of cocky cockity n of conding this of this其他库)。

您那里有很多问题。

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