我怎么使用STL算法与指针的向量 [英] how do I use STL algorithms with a vector of pointers
问题描述
我有不是由容器所拥有的指针向量。如何使用上指针的目标算法。我试图用升压的ptr_vector,但它会尝试当它超出范围,删除指针。
I have a vector of pointers that are not owned by the container. How do I use algorithms on the targets of the pointers. I tried to use boost's ptr_vector, but it tries to delete the pointers when it goes out of scope.
下面是一些code,需要工作:
Here is some code that needs to work:
vector<int*> myValues;
// ... myValues is populated
bool consistent = count(myValues.begin(), myValues.end(), myValues.front()) == myValues.size();
auto v = consistent ? myValues.front() : accumulate(myValues.begin(), myValues.end(), 0) / myValues.size();
fill(myValues.begin(), myValues.end(), v);
// etc.
我认识到,对循环的工作,但这种情况发生在一堆的地方,所以某种一元的适配器?我没能找到一个。在此先感谢!
I realize that for loops would work, but this happens in a bunch of places, so some kind of unary adapter? I wasn't able to find one. Thanks in advance!
推荐答案
您可以使用的Boost间接迭代器。当解除引用(使用的operator *()
),它适用的额外的的解引用,所以你最终由指针指向的值由引用迭代器。欲了解更多信息,你还可以看到这个问题有关解引用迭代器
You could use Boost Indirect Iterator. When dereferenced (with operator*()
), it applies an extra dereference, so you end up with the value pointed by the pointer referenced by the iterator. For more information, you can also see this question about a dereference iterator.
下面是一个简单的例子:
Here's a simple example:
std::vector<int*> vec;
vec.push_back(new int(1));
vec.push_back(new int(2));
std::copy(boost::make_indirect_iterator(vec.begin()),
boost::make_indirect_iterator(vec.end()),
std::ostream_iterator<int>(std::cout, " ")); // Prints 1 2
这篇关于我怎么使用STL算法与指针的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!