Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing std::vector with ranges library

Tags:

c++

c++20

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?

like image 300
Paul Jurczak Avatar asked May 16 '20 18:05

Paul Jurczak


People also ask

What is the correct way to initialize vector?

Algorithm. Begin Initialize a variable s. Create a vector v with size s and all values with 7. Initialize vector v1 by array.


1 Answers

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.

like image 191
Davis Herring Avatar answered Sep 23 '22 09:09

Davis Herring