如何解决关于Lambda与boost :: adaptors :: filtered结合使用的两个问题
请考虑以下非编译代码:
#include <boost/range/adaptors.hpp>
class Stuff {
public:
bool var;
};
class Manager {
/// Get everything
std::vector<Stuff*>
get_all_stuff() const
{
return list_of_stuff;
}
/// Get a vector of only those that whose "var" matches the "tf" argument.
std::vector<Stuff*>
get_some_stuff(const bool tf) const
{
return (get_all_stuff() |
boost::adaptors::filtered(
[](Stuff const& s) { return (s.var == tf); }
)
);
}
private:
std::vector<Stuff*> list_of_stuff;
};
编译死于此错误:
ex.cc: In lambda function:
ex.cc:21:46: error: ‘tf’ is not captured
[](Stuff const& s) { return (s.var == tf); }
^
1。)如何将那个函数参数引入我的lambda中?
2。)这是危险的方法吗?我应该改用std :: remove_copy_if()吗?
- 我不担心“ get_all_stuff()”返回的向量的寿命。
- 我担心“ get_some_stuff()”返回的向量的寿命。
解决方法
要将外部值转化为lambda,必须捕获它。
[&tf](Stuff const& s) { return (s.var == tf);
在示例中,我使用了boost::adaptors::filter
。但是以太一个将返回一个范围,而不是矢量对象。如果要返回与list_of_stuff
不同的向量,则必须构建它。如果从函数返回它,则编译器将在可能的情况下移动它。这是工作中的example on coliru。
#include <iostream>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
class Stuff {
public:
bool var;
int id;
};
std::ostream& operator << (std::ostream& os,const Stuff stuff) {
return os << std::boolalpha << stuff.id << " " << stuff.var;
}
using vector_type = std::vector<Stuff>;
class Manager {
/// Get everything
public:
auto get_all_stuff() const
{
return list_of_stuff;
}
// Get a vector of only those that whose "var" matches the "tf" argument.
vector_type get_some_stuff(const bool tf) const
{
vector_type temp;
for (auto item : boost::adaptors::filter(list_of_stuff,[&tf](Stuff const& s) { return s.var == tf; }))
temp.push_back(item);
return temp;
}
private:
vector_type list_of_stuff = { {false,1},{true,2},{false,3},4},5} };
};
int main()
{
Manager manage;
for (const auto item : manage.get_all_stuff())
std::cout << item << " ";
std::cout << std::endl;
for (const auto item : manage.get_some_stuff(true))
std::cout << item << " ";
std::cout << std::endl;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。