关于在 lambda 表达式中使用智能指针的问题

zhcosin 2013-08-07 05:25:48
问题是这样的,boost::lambda 表达式很适合用来作为标准库泛型算法中的函数对象,以 std::find_if 为例,假定有一个结构

class T
{
string id;
//......
};

然后有一个 std::vector

std::vector<T> v;

如果我要在这个容器中查找成员 id 的值等于 id_value 的元素,可以这样写

std::vector<T>::const_iterator it = std::find_if(v.begin(), v.end(),
boost::lambda::bind(&T::id, boost::lambda::_1) == id_value);

如果这个容器里不是直接存放的元素,而是存放的元素的原始指针,那么可以这样写

std::vector<T*>::const_iterator it = std::find_if(v.begin(), v.end(),
(boost::lambda::_1->* &T::id) == id_value);

但是如果容器里存放的不是原始指针,而是智能指针 boost::shared_ptr<T>,请问同样的操作该如何书写 lambda 表达式,求指点?
...全文
392 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhcosin 2013-08-09
  • 打赏
  • 举报
回复
引用 7 楼 ri_aje 的回复:
dereferencing a shared_ptr gives the managed type.

std::vector<boost::shared_ptr<T>> v;
std::find_if(v.begin(),v.end(),boost::lambda::bind(&T::id,*boost::lambda::_1) == "test");
灰常灰常感谢。。。
mujiok2003 2013-08-07
  • 打赏
  • 举报
回复
template <class InputIterator, class UnaryPredicate>
   InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
要求:Unary function that accepts an element in the range as argument and returns a value convertible to bool. The value returned indicates whether the element is considered a match in the context of this function. The function shall not modify its argument. This can either be a function pointer or a function object.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <memory>

struct T
{
	std::string id;
};


int main( )
{
	{
		std::vector<T> v;
		auto i = std::find_if(v.begin(),v.end(), 
			[](T const& t) -> bool { return t.id == "that id";}
		);
	}
	{
		std::vector<std::shared_ptr<T> > v;
		auto i = std::find_if(v.begin(),v.end(), 
			[](std::shared_ptr<T> const& t) -> bool { return t->id == "that id";}
		);
	}

	return 0;
}

ri_aje 2013-08-07
  • 打赏
  • 举报
回复
dereferencing a shared_ptr gives the managed type.

std::vector<boost::shared_ptr<T>> v;
std::find_if(v.begin(),v.end(),boost::lambda::bind(&T::id,*boost::lambda::_1) == "test");
qq120848369 2013-08-07
  • 打赏
  • 举报
回复
boost这个lambda好变态的样子, 还是C++11的简单.
taodm 2013-08-07
  • 打赏
  • 举报
回复
你这个应该使用c++2011标准的lambda函数,而不是boost库了。
zhcosin 2013-08-07
  • 打赏
  • 举报
回复
引用 3 楼 taodm 的回复:
好吧,楼主V5
没说你,只是反感二楼那没事找抽型的货。
taodm 2013-08-07
  • 打赏
  • 举报
回复
好吧,楼主V5
zhcosin 2013-08-07
  • 打赏
  • 举报
回复
引用 1 楼 zhao4zhong1 的回复:
lambda表达式是语法糖。 语法糖越甜,编译调试查错越苦! 个人意见:“模版和泛型技术”和“lambda表达式技术”都比不上“code generation代码生成”技术。
不会的哪凉快哪呆着去。
赵4老师 2013-08-07
  • 打赏
  • 举报
回复
lambda表达式是语法糖。 语法糖越甜,编译调试查错越苦! 个人意见:“模版和泛型技术”和“lambda表达式技术”都比不上“code generation代码生成”技术。

64,671

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧