使用boost::adaptors链获取std::list的boost范围,可以通过以下步骤实现:
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/for_each.hpp>
#include <boost/range/algorithm_ext/push_back.hpp>
#include <boost/range/algorithm_ext/insert.hpp>
#include <boost/range/algorithm_ext/erase.hpp>
#include <boost/range/algorithm_ext/replace.hpp>
#include <boost/range/algorithm_ext/remove.hpp>
#include <boost/range/algorithm_ext/unique.hpp>
#include <boost/range/algorithm_ext/sort.hpp>
#include <boost/range/algorithm_ext/merge.hpp>
#include <boost/range/algorithm_ext/for_each.hpp>
#include <boost/range/algorithm_ext/iota.hpp>
#include <boost/range/algorithm_ext/insert.hpp>
#include <boost/range/algorithm_ext/erase.hpp>
#include <boost/range/algorithm_ext/replace.hpp>
#include <boost/range/algorithm_ext/remove.hpp>
#include <boost/range/algorithm_ext/unique.hpp>
#include <boost/range/algorithm_ext/sort.hpp>
#include <boost/range/algorithm_ext/merge.hpp>
#include <boost/range/algorithm_ext/for_each.hpp>
#include <boost/range/algorithm_ext/iota.hpp>
std::list<int> myList;
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);
myList.push_back(4);
myList.push_back(5);
auto range = myList | boost::adaptors::transformed([](int i) { return i * 2; })
| boost::adaptors::filtered([](int i) { return i % 3 == 0; });
在上述代码中,我们使用了boost::adaptors::transformed来将std::list中的每个元素乘以2,然后使用boost::adaptors::filtered来筛选出能被3整除的元素。
boost::range::for_each(range, [](int i) { std::cout << i << " "; });
上述代码将打印出符合条件的元素,即6。
完整示例代码如下:
#include <iostream>
#include <list>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm/for_each.hpp>
int main() {
std::list<int> myList;
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);
myList.push_back(4);
myList.push_back(5);
auto range = myList | boost::adaptors::transformed([](int i) { return i * 2; })
| boost::adaptors::filtered([](int i) { return i % 3 == 0; });
boost::range::for_each(range, [](int i) { std::cout << i << " "; });
return 0;
}
这样,我们就使用boost::adaptors链获取了std::list的boost范围,并对范围进行了操作和打印结果。
领取专属 10元无门槛券
手把手带您无忧上云