Is this the correct way to declare vector array in C++?
Yes, your declaration is correct for initializing a std::vector in C++. Here's what your code does:
#include <vector>
#include <iostream>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int num : nums) {
std::cout << num << " ";
return 0;
Explanation:
- std::vector<int>: Declares a vector that holds integers.
- {1, 2, 3, 4, 5, 6, 7, 8, 9}: This is a list initializer, also known as uniform initialization or
brace-enclosed initializer, which initializes the vector with the specified values.
Output:
The nums vector will contain the elements [1, 2, 3, 4, 5, 6, 7, 8, 9]. If you print them, you will see the
same sequence.
This syntax is valid since C++11. If you're using an older version of C++, you would need to initialize
the vector differently.