简体   繁体   English

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

[英]how do I use STL algorithms with a vector of pointers

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. 我尝试使用boost的ptr_vector,但它会在超出范围时尝试删除指针。

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? 我意识到for循环可以工作,但这发生在一堆地方,所以某种一元的适配器? I wasn't able to find one. 我找不到一个。 Thanks in advance! 提前致谢!

You could use Boost Indirect Iterator . 您可以使用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. 取消引用时(使用operator*() ),它会应用额外的解除引用,因此最终会得到迭代器引用的指针指向的值。 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
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));

Fill can't take assign function (so that it would dereference pointers). 填充不能采用赋值函数(因此它会取消引用指针)。 Therefore for_each() was used. 因此使用了for_each()。 For optimization it would be wise to add if(!consistent) before running for_each(). 为了优化,在运行for_each()之前添加if(!consistent)是明智的。 Functions used in above STL one liners: 以上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; }

You can look at boost::shared_ptr<> - a smart pointer with reference counting. 您可以查看boost::shared_ptr<> - 一个带引用计数的智能指针。 It will not delete the pointer after it goes out of scope. 它超出范围后不会删除指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM