Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to insert a consecutive inter range into std::vector?

Tags:

c++

c++17

Say I want all numbers from 23 to 57 be in a vector. I can do this:

vector<int> result;
for (int i = 23; i <= 57; ++i)
{
    result.push_back(i);
}

But this is a 5 line solution for a simple job. Can't I do that more elegantly? The best syntax would be vector<int> result{23 .. 57}; for example or such a trivial one line code. Any options with C++17?

like image 767
Narek Avatar asked May 16 '18 07:05

Narek


2 Answers

You can use std::iota (since C++11).

Fills the range [first, last) with sequentially increasing values, starting with value and repetitively evaluating ++value.

The function is named after the integer function ⍳ from the programming language APL.

e.g.

std::vector<int> result(57 - 23 + 1);
std::iota(result.begin(), result.end(), 23);
like image 57
songyuanyao Avatar answered Sep 21 '22 09:09

songyuanyao


With range-v3, it would be:

const std::vector<int> result = ranges::view::ints(23, 58); // upper bound is exclusive

With C++20, std::ranges::iota_view:

const auto result1 = std::ranges::views::iota(23, 58); // upper bound is exclusive
const auto result2 = std::ranges::iota_view(23, 58); // upper bound is exclusive
like image 25
Jarod42 Avatar answered Sep 17 '22 09:09

Jarod42