how to scan vector in c++
Scanning a Vector in C++
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
int n, x;
std::cout << "Enter the number of elements: ";
std::cin >> n;
std::cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
std::cin >> x;
vec.push_back(x);
}
std::cout << "The elements in the vector are: ";
for (int i = 0; i < vec.size(); i++) {
std::cout << vec[i] << " ";
}
return 0;
}
- Include necessary libraries:
#include <iostream>
: This header file allows input and output operations.#include <vector>
: This header file allows the use of vectors.Define the main function:
int main() { ... }
: This is the entry point of the program.Declare a vector and variables:
std::vector<int> vec;
: Declares a vector named "vec" that stores integers.int n, x;
: Declares integer variables "n" and "x" to store the number of elements and the current input element, respectively.Prompt for the number of elements:
std::cout << "Enter the number of elements: ";
: Displays a message asking the user to input the number of elements.Read the number of elements:
std::cin >> n;
: Reads the input number of elements from the user.Prompt for the elements and populate the vector:
std::cout << "Enter the elements: ";
: Displays a message asking the user to input the elements.for (int i = 0; i < n; i++) { ... }
: Loops through the input elements.std::cin >> x;
: Reads the input element from the user.vec.push_back(x);
: Adds the input element to the vector.
Display the elements in the vector:
std::cout << "The elements in the vector are: ";
: Displays a message indicating the elements about to be printed.for (int i = 0; i < vec.size(); i++) { ... }
: Loops through the elements in the vector.std::cout << vec[i] << " ";
: Prints each element of the vector.
Return from main:
return 0;
: Indicates successful execution and termination of the program.