To create a vector of size N in C++, you can use the std::vector
class from the Standard Template Library (STL) and initialize it with a specific size and optional default value.
In this example,
header to use the std::vector
class.std::vector
and provide the size n
as an argument to the constructor. This initializes the vector with n
elements, each set to 0 by default.int_vector
.#include <iostream>
#include <vector>
int main() {
size_t n = 5;
std::vector<int> int_vector(n);
for (int num : int_vector) {
std::cout << num << " ";
}
return 0;
}
0 0 0 0 0
In this example,
and
headers to use the std::vector
and std::string
classes.std::vector
and provide the size n
as an argument to the constructor. This initializes the vector with n
elements, each set to an empty string ""
by default.str_vector
.#include <iostream>
#include <vector>
#include <string>
int main() {
size_t n = 5;
std::vector<std::string> str_vector(n);
for (const std::string& str : str_vector) {
std::cout << '"' << str << '"' << " ";
}
return 0;
}
"" "" "" "" ""
In this example,
header to use the std::vector
class.std::vector
and provide the size n
as an argument to the constructor. This initializes the vector with n
elements, each set to false
by default.bool_vector
.#include <iostream>
#include <vector>
int main() {
size_t n = 5;
std::vector<bool> bool_vector(n);
for (bool val : bool_vector) {
std::cout << std::boolalpha << val << " ";
}
return 0;
}
false false false false false
In this tutorial, we learned How to create a Vector of Size N in C++ language with well detailed examples.