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;
}
  1. Include necessary libraries:
  2. #include <iostream>: This header file allows input and output operations.
  3. #include <vector>: This header file allows the use of vectors.

  4. Define the main function:

  5. int main() { ... }: This is the entry point of the program.

  6. Declare a vector and variables:

  7. std::vector<int> vec;: Declares a vector named "vec" that stores integers.
  8. int n, x;: Declares integer variables "n" and "x" to store the number of elements and the current input element, respectively.

  9. Prompt for the number of elements:

  10. std::cout << "Enter the number of elements: ";: Displays a message asking the user to input the number of elements.

  11. Read the number of elements:

  12. std::cin >> n;: Reads the input number of elements from the user.

  13. Prompt for the elements and populate the vector:

  14. std::cout << "Enter the elements: ";: Displays a message asking the user to input the elements.
  15. 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.
  16. Display the elements in the vector:

  17. std::cout << "The elements in the vector are: ";: Displays a message indicating the elements about to be printed.
  18. 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.
  19. Return from main:

  20. return 0;: Indicates successful execution and termination of the program.