C++

C++ : Vector Initialization

Different ways of initializing a vector


1. Initialize the vector using values.

#include<iostream>
#include<vector>

int main() {

    std :: vector<char> letters { 'S', 'H', 'E', 'B', 'A', 'N', 'G' };
    for (const auto& l : letters) {
        std :: cout << l << " ";
    } std :: cout << std :: endl;

    std :: vector<int> numbers { 7, 55, 32, 9, 31 };
    for (const auto& n : numbers) {
        std :: cout << n << " ";
    }

    return 0;
}

Output

S H E B A N G 
7 55 32 9 31

2. Initialize the vector using an existing array

#include<iostream>
#include<vector>

int main() {

    // Initializing vector using an existing char array 
    char carr[] = { 'O', 'S', 'C', 'A', 'R', 'S', 'L', 'A', 'P' };
    std :: vector<char> letters (carr, carr + sizeof(carr) / sizeof(carr[0]));

    for (const auto& l : letters) {
        std :: cout << l << " ";
    } std :: cout << std :: endl;

    // Initializing vector using an existing int array 
    char narr[] = { 44, 23, 46, 8, 90 };
    std :: vector<int> numbers (narr, narr + sizeof(narr) / sizeof(narr[0]));

    for (const auto& n : numbers) {
        std :: cout << n << " ";
    }

    return 0;
}

Output

O S C A R S L A P 
44 23 46 8 90

3. Initialize a vector with a value during creation.

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>

int main() {
    
    size_t sz = 3;
    std :: vector<std::string> vec_oscar(sz, "slap");

    for (const auto& val : vec_oscar) {
         std :: cout << val << " ";
    }
    
    return 0;
}

Output

slap slap slap

4. Filling a vector with a specific value using fill function.

Prototype : void fill ( ForwardIterator start, ForwardIterator end, const T& val );

#include<iostream>
#include<vector>
#include<algorithm>

int main() {
    
    std :: vector<int> nums(15);
    std :: fill (nums.begin(), nums.end(), 6039);

    for (const auto& n : nums) {
        std :: cout << n << " ";
    } std :: cout << std :: endl;


    std :: vector<char> letters(10);
    std :: fill (letters.begin(), letters.end(), 'P');

    for (const auto& l : letters) {
        std :: cout << l << " ";
    }

    return 0;
}   

Output

6039 6039 6039 6039 6039 6039 6039 6039 6039 6039 6039 6039 6039 6039 6039 
P P P P P P P P P P

5. Initialize a vector using an existing vector.

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>

int main() {

    std :: vector<std::string> vec_material {"straw", "stick", "brick"};

    std :: vector<std::string> vec_piggy_house_make (vec_material.begin(),  vec_material.end());

    for (const auto& make : vec_piggy_house_make) {
         std :: cout << "Piggy house made from " << make << std :: endl;
    }
    return 0;
}

Output

Piggy house made from straw
Piggy house made from stick
Piggy house made from brick


Copyright (c) 2019-2023, Algotree.org.
All rights reserved.