Initializing std::vector with ranges library

China☆狼群 提交于 2020-06-14 06:57:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!