问题
I would like to initialize std::vector
with a range of consecutive integers without typing all of them, something like a second line, which doesn't compile, in this code snippet:
std::vector<int> a{0, 1, 2, 3, 4, 5};
std::vector<int> b{std::ranges::iota_view(0, 5)}; // ERROR!
Of course, I would greatly prefer:
std::vector<int> b{0:5};
but this is not scheduled before C++41 standard. Any ideas how to do it in C++20?
回答1:
What you’re looking for is
auto b=std::ranges::to<std::vector>(std::ranges::iota_view(0, 5));
Unfortunately, that proposal missed C++20 simply because there wasn’t time to review its wording (after a previous version that added the constructor you tried was found unworkable). Hopefully it’ll be merged—and implemented—early in the C++23 cycle.
来源:https://stackoverflow.com/questions/61841418/initializing-stdvector-with-ranges-library