C++ – how to use STL algorithms with a vector of pointers

boostcc++11lambdastl

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.

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!

Best Answer

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