以下是范围库的示例:
范围 V3
Live On Wandbox
#include <range/v3/all.hpp>
#include <iostream>
#include <cstdio>
using namespace std::string_literals;
using namespace ranges::v3;
using std::vector;
int main() {
auto print = [](auto const& v) { std::cout << v << "\n"; };
for(auto sz : { "a", "b" }) print(sz);
for_each({"a", "b"}, print);
vector v { 1, 2, 3, 4, 5 };
auto chain =
view::transform([](auto i) { return i*2; })
| view::filter([](auto i) -> bool { return i % 3; });
for_each(v | chain, print);
auto constexpr Range = view::iota;
for_each(Range(12, 24) | chain, print);
}
打印
a
b
a
b
2
4
8
10
26
28
32
34
38
40
44
46
提升范围
Live On Wandbox
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/irange.hpp>
#include <iostream>
using namespace boost::adaptors;
using std::vector;
int main() {
auto print = [](auto const& v) { std::cout << v << "\n"; };
for(auto sz : { "a", "b" }) print(sz);
boost::for_each(vector {"a", "b"}, print);
vector v { 1, 2, 3, 4, 5 };
boost::for_each(v
| transformed([](auto i) { return i*2; })
| filtered([](auto i) -> bool { return i % 3; }),
print);
for_each(boost::irange(12, 24)
| transformed([](auto i) { return i*2; })
| filtered([](auto i) -> bool { return i % 3; }),
print);
}
请注意,我们不存储表达式模板,因为 Boost 的
设施不能很好地处理临时性(Range v3 生成
不安全使用的编译错误)。
打印
a
b
a
b
2
4
8
10
26
28
32
34
38
40
44
46
为了纯粹的乐趣
您可以使用纯 C++03 中的各种 Boost 库来做同样的事情:
Live On Coliru
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/irange.hpp>
#include <boost/array.hpp>
#include <boost/foreach.hpp>
#include <boost/assign.hpp>
#include <boost/phoenix.hpp>
#include <iostream>
using namespace boost::adaptors;
using namespace boost::phoenix::arg_names;
using std::vector;
int main() {
char const* ab[] = { "a", "b" };
// who needs c++11 for ranged-for?
BOOST_FOREACH(char const* sz, ab) std::cout << sz << "\n";
// who needs c++11 for lambdas?
boost::for_each(ab, std::cout << arg1 << "\n");
// who needs c++11 for initializer lists?
vector<int> v;
using boost::assign::operator+=; // very dubious magic, but hey, we're having fun
v += 1, 2, 3, 4, 5;
// etc.
boost::for_each(v | transformed(arg1 * 2) | filtered(arg1 % 3), std::cout << arg1 << "; ");
std::cout << '\n';
boost::for_each(boost::irange(12, 24) | transformed(arg1 * 2) | filtered(arg1 % 3), std::cout << arg1 << "; ");
std::cout << '\n';
}
打印
a
b
a
b
2; 4; 8; 10;
26; 28; 32; 34; 38; 40; 44; 46;