如何将STL算法与指针向量一起使用

时间:2009-05-07 07:15:51

标签: c++ stl boost lambda c++11

我有一个不属于容器的指针向量。如何在指针的目标上使用算法。我尝试使用boost的ptr_vector,但它会在超出范围时尝试删除指针。

以下是一些需要工作的代码:

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.

我意识到for循环可以工作,但这发生在很多地方,所以某种一元的适配器?我找不到一个。提前谢谢!

3 个答案:

答案 0 :(得分:19)

您可以使用Boost Indirect Iterator。取消引用时(使用operator*()),它会应用额外的取消引用,因此最终会得到迭代器引用的指针所指向的值。有关详细信息,您还可以查看this question about a dereference iterator

这是一个简单的例子:

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

答案 1 :(得分:3)

bool consistent = count_if(myValues.begin(), myValues.end(), 
   bind2nd(ptr_fun(compare_ptr), *myValues.front())) == myValues.size();

int v = consistent ? *myValues.front() : accumulate(
   myValues.begin(), myValues.end(), 0, sum_int_ptr) / myValues.size();

for_each(myValues.begin(), myValues.end(), bind1st(ptr_fun(assign_ptr),v));

填充不能采用赋值函数(因此它会取消引用指针)。因此使用了for_each()。为了优化,在运行for_each()之前添加if(!consistent)是明智的。上述STL一个衬里中使用的函数:

int sum_int_ptr(int total, int * a) { return total + *a; }    
void assign_ptr(int v, int *ptr) { *ptr = v; }    
bool compare_ptr(int* a, int pattern) { return *a == pattern; }

答案 2 :(得分:0)

您可以查看boost::shared_ptr<> - 带引用计数的智能指针。它超出范围后不会删除指针。