I am especially interested in adaptor for a following use case:
我对以下用例的适配器特别感兴趣:
std::list<int> input {1, 2, 3};
std::list<int> result;
auto l = [](auto e) { return e + 1; };
result.insert(result.end(), adaptor(input.begin(), l), adaptor(input.end(), l));
// now result == {2, 3, 4}
It would be nice if the adaptor would not use external libraries (e.g. boost).
如果适配器不使用外部库(例如boost)会很好。
2 个解决方案
#1
4
Your question is tagged C++14, and says that no external library dependence would be great (fair enough).
你的问题被标记为C ++ 14,并且说没有外部库依赖会很好(足够公平)。
For future reference, though, note that the range
library seems well on its way toward adoption by the standard library (the C++17 range for loop is already compliant with one of its major points). So, using range
, the code could look like this:
但是,为了将来参考,请注意,范围库似乎正在向标准库采用(C ++ 17 range for loop已经符合其主要要点之一)。因此,使用范围,代码可能如下所示:
#include <list>
#include <range/v3/all.hpp>
int main() {
const std::list<int> input{1, 2, 3};
const std::list<int> result =
input | ranges::view::transform([](int i){ return i + 1; });
}
and it's what future standard library C++ code is likely to be. Irrespectively, it has its advantages:
这就是未来标准库C ++代码的可能性。无论如何,它有其优点:
-
It looks more intuitive (although that might be subjective).
它看起来更直观(虽然这可能是主观的)。
-
Note how you can make
result
const
.注意如何使结果const。
#2
2
So using PiotrSkotnicki advice I end up with a code like this:
所以使用PiotrSkotnicki建议我最终得到这样的代码:
#include <algorithm>
#include <iterator>
#include <list>
int main() {
std::list<int> input {1, 2, 3};
std::list<int> output;
std::transform(input.begin(), input.end(), std::back_inserter(output), [](auto e){ return e + 1;});
}
#1
4
Your question is tagged C++14, and says that no external library dependence would be great (fair enough).
你的问题被标记为C ++ 14,并且说没有外部库依赖会很好(足够公平)。
For future reference, though, note that the range
library seems well on its way toward adoption by the standard library (the C++17 range for loop is already compliant with one of its major points). So, using range
, the code could look like this:
但是,为了将来参考,请注意,范围库似乎正在向标准库采用(C ++ 17 range for loop已经符合其主要要点之一)。因此,使用范围,代码可能如下所示:
#include <list>
#include <range/v3/all.hpp>
int main() {
const std::list<int> input{1, 2, 3};
const std::list<int> result =
input | ranges::view::transform([](int i){ return i + 1; });
}
and it's what future standard library C++ code is likely to be. Irrespectively, it has its advantages:
这就是未来标准库C ++代码的可能性。无论如何,它有其优点:
-
It looks more intuitive (although that might be subjective).
它看起来更直观(虽然这可能是主观的)。
-
Note how you can make
result
const
.注意如何使结果const。
#2
2
So using PiotrSkotnicki advice I end up with a code like this:
所以使用PiotrSkotnicki建议我最终得到这样的代码:
#include <algorithm>
#include <iterator>
#include <list>
int main() {
std::list<int> input {1, 2, 3};
std::list<int> output;
std::transform(input.begin(), input.end(), std::back_inserter(output), [](auto e){ return e + 1;});
}