How to initialize a vector with a range of numbers in C++

3 Answers

0 votes
#include <iostream>
#include <vector>
#include <numeric>   // std::iota lives here

// Build a sequence [start, end) using std::iota.
// Uses a standard algorithm that is efficient and easy to recognize.
std::vector<int> make_range_iota(int start, int end) {
    // end is exclusive: [start, end)
    const int size = end - start;
    std::vector<int> values(size);

    // Fill the vector with consecutive integers beginning at 'start'.
    // std::iota is part of <numeric>, so we include that header above.
    std::iota(values.begin(), values.end(), start);

    return values;
}

// Build a sequence [start, end) using a simple loop.
// This is straightforward and works in all environments.
std::vector<int> make_range_loop(int start, int end) {
    std::vector<int> values;
    values.reserve(end - start); // reserve capacity to avoid repeated reallocations

    for (int n = start; n < end; ++n) {
        values.push_back(n);
    }

    return values;
}

// Print a sequence for demonstration.
void print_range(const std::vector<int>& values) {
    for (int v : values) {
        std::cout << v << ' ';
    }
    std::cout << '\n';
}

int main() {
    // Build ranges using both approaches.
    auto a = make_range_iota(1, 10);
    auto b = make_range_loop(1, 10);

    // Display results.
    std::cout << "Using std::iota: ";
    print_range(a);

    std::cout << "Using loop:      ";
    print_range(b);
}



/*
run:

Using std::iota: 1 2 3 4 5 6 7 8 9 
Using loop:      1 2 3 4 5 6 7 8 9 

*/

 



answered Aug 17 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <numeric> // Required for std::iota

int main() {
    // 1. Create a vector of size 5
    std::vector<int> vec(5); 

    // 2. Fill it with numbers starting at 10 (Result: 10, 11, 12, 13, 14)
    std::iota(vec.begin(), vec.end(), 10); 

    for (int num : vec) {
        std::cout << num << " ";
    }
}


/*
run:

10 11 12 13 14 

*/

 



answered Aug 17 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <algorithm> // Required for std::generate

int main() {
    std::vector<int> vec(5);
    int value = 0;
    
    // Fill the vector incrementing by 2 each step
    std::generate(vec.begin(), vec.end(), [&value]() {
        int current = value;
        value += 2;

        return current;
    }); // Result: 0, 2, 4, 6, 8

    for (int num : vec) {
        std::cout << num << " ";
    }
}



/*
run:

0 2 4 6 8 

*/

 



answered Aug 17 by avibootz
edited Aug 17 by avibootz
...