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

  • A+

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?

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.


std::vector<int> result(57 - 23 + 1); std::iota(result.begin(), result.end(), 23); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: