0

我有一个指向对象的指针向量,并且在某个时候,使用该向量的子元素创建第二个向量。现在,对原始向量进行排序会更改第二个向量中的元素(排序后其中的元素完全不同)。

这是预期的行为吗?它与make_indirect_iterator有关吗?有没有更好的解决方案(假设我想保留一个指针向量)?

std::vector<std::shared_ptr<MyObj>> vecAll;
std::vector<std::shared_ptr<MyObj>> vecSub;

// fill vecAll with something...

for(auto obj : vecAll) {
    if( obj->x >=0 ) {
        vecSub.push_back(obj);
    }
}

// 3 objects in 'vecSub'

std::sort(boost::make_indirect_iterator(vecAll.begin()), boost::make_indirect_iterator(vecAll.end()), std::greater<MyObj>());

// now there are 3 DIFFERENT objects in 'vecSub'
4

1 回答 1

6

是的,它与make_indirect_iterator. 这会导致对象值被交换,而不仅仅是重新排序指针。

您可以改为使用普通迭代器并在比较步骤中执行取消引用。Lambda 让这变得更容易:

typedef decltype(vecAll.front()) iter;
std::sort(vecAll.begin(),
          vecAll.end(),
          [](iter a, iter b) { return *a > *b; });

带有可重用仿函数的版本(感谢 MooingDuck 的建议):

struct indirect_greater
{
    template<typename iter>
    bool operator()(iter a, iter b) const { return *a > *b; }
};

std::sort(vecAll.begin(), vecAll.end(), indirect_greater());

C++14 添加了多态 lambda,它可以让您编写一个短 lambda [](a, b)(*a > *b),其行为类似于第二个(仿函数)解决方案。无需命名迭代器类型(例如 with decltype)。

于 2013-05-13T19:51:11.803 回答