C++ how to declare and initialize vectors
To declare and initialize a vector in C++, you can use curly braces ({}) or the std::vector
constructor.
Here are some examples:
refer to:theitroad.com#include <iostream> #include <vector> int main() { // Initialize vector with default values std::vector<int> v1; // empty vector // Initialize vector with a given number of elements std::vector<int> v2(5); // vector of 5 elements, initialized to 0 std::vector<int> v3(5, 10); // vector of 5 elements, initialized to 10 // Initialize vector with an initializer list std::vector<int> v4 = {1, 2, 3}; // vector of 3 elements, initialized to 1, 2, and 3 std::vector<int> v5{1, 2, 3}; // vector of 3 elements, initialized to 1, 2, and 3 // Initialize vector from another vector std::vector<int> v6(v4); // copy of v4 // Output the vectors std::cout << "v1: "; for (int i : v1) std::cout << i << " "; std::cout << std::endl; std::cout << "v2: "; for (int i : v2) std::cout << i << " "; std::cout << std::endl; std::cout << "v3: "; for (int i : v3) std::cout << i << " "; std::cout << std::endl; std::cout << "v4: "; for (int i : v4) std::cout << i << " "; std::cout << std::endl; std::cout << "v5: "; for (int i : v5) std::cout << i << " "; std::cout << std::endl; std::cout << "v6: "; for (int i : v6) std::cout << i << " "; std::cout << std::endl; return 0; }
Output:
v1: v2: 0 0 0 0 0 v3: 10 10 10 10 10 v4: 1 2 3 v5: 1 2 3 v6: 1 2 3
In the above example, v1
is an empty vector, v2
is a vector of 5 elements initialized to 0, v3
is a vector of 5 elements initialized to 10, v4
and v5
are vectors of 3 elements initialized to 1, 2, and 3, and v6
is a copy of v4
. Note that the for
loops are using range-based for loops to iterate over the elements of the vectors.