简体   繁体   中英

How to store a sequence of integers in a C++ array?

Assume I have to store 100 integers in array, should I declare an array and store all 100 integers from 1 to 100 or is there any solution that will work better ? and loop them through a for loop or any loop concept in c++

example

   int numbers [100] = { 1 ,2 3,......10};
for(){
//manipulate the array elements here
}

or

int numbers = {100};

what if I have more than 100 elements ? ie integer number from 1 to 200 or more what is good concept to achieve ?

You can use std::iota to generate a sequence.

For example, like this:

#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> vec(100);
    std::iota(begin(vec), end(vec), 1);
    for (auto i : vec)
        std::cout << i << " ";
    std::cout << "\n";
}

If you have to use a raw array, you can fill it like this:

int vec[100];
std::iota(vec, vec + 100, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM