如何将 STL 算法与指针向量结合使用
我有一个不属于容器的指针向量。 如何对指针的目标使用算法。 我尝试使用 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 循环可以工作,但是这种情况发生在很多地方,所以某种一元适配器? 我没能找到一个。 提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 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:
Fill 不能接受分配函数(这样它就会取消引用指针)。 因此使用了 for_each() 。 为了优化,明智的做法是在运行 for_each() 之前添加 if(!consistent)。 上述STL oneliner中使用的函数:
Fill can't take assign function (so that it would dereference pointers). Therefore for_each() was used. For optimization it would be wise to add if(!consistent) before running for_each(). Functions used in above STL one liners:
您可以查看
boost::shared_ptr<>
- 具有引用计数的智能指针。 超出范围后它不会删除指针。You can look at
boost::shared_ptr<>
- a smart pointer with reference counting. It will not delete the pointer after it goes out of scope.