用std ::排序迭代器
sorting iterators with std::sort
我想对含有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其他库)。
您那里有很多问题。
-
最明显的是您的代码缺乏
[this]
。 -
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)
}
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 无法使用自定义迭代器进行排序
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- 在C++中使用迭代器合并排序
- 使用迭代器进行合并排序中的一个缓冲区
- 如何使equal_range迭代器在 Boost 多索引中按不同的索引排序?
- 使用迭代器对 std::list 进行排序
- 如何对迭代器的模板专业化进行排序?
- 使用迭代器 c++ 进行排序
- 用std ::排序迭代器
- 创建一个C++预排序迭代器,为循环提供树节点
- 我正在尝试为我的 DynamicArray 类创建一个迭代器。为什么 STL 排序不适用于我的迭代器?
- C++迭代器的未排序修改
- 在双向迭代器上实现快速排序
- 实现基于迭代器的 shell 排序
- 使用迭代器通过比较对向量进行排序
- 排序后的数据结构通过迭代器快速迭代、插入、删除
- 堆排序向量的客户端,传递迭代器不正确
- Vector迭代器在实现快速排序时不可解引用