how to input a vector when size is unknown
To input a vector in C++ when the size is unknown, you can follow the steps below:
- Include the necessary header files:
#include <iostream>
#include <vector>
The iostream
header file is required for input and output operations, while the vector
header file is needed to work with vectors.
- Declare an empty vector:
std::vector<int> vec;
Here, std::vector<int>
declares a vector of integers named vec
.
- Read input values using a loop:
int num;
while (std::cin >> num) {
vec.push_back(num);
}
This loop reads input values from the user until the input stream (std::cin
) is valid. The input values are then added to the vector using the push_back
function.
- Access the vector elements: You can access the elements of the vector using the square bracket notation ([]):
for (int i = 0; i < vec.size(); i++) {
std::cout << vec[i] << " ";
}
This loop iterates over the vector and prints each element.
Putting it all together, here's a complete example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
int num;
while (std::cin >> num) {
vec.push_back(num);
}
for (int i = 0; i < vec.size(); i++) {
std::cout << vec[i] << " ";
}
return 0;
}
This code will read integers from the user until the input stream is valid, store them in the vector, and then print the vector elements.