insert only unique values into vector

Code to Insert Only Unique Values into a Vector in C++

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec;
    int newValue;

    while (std::cin >> newValue) {
        if (std::find(vec.begin(), vec.end(), newValue) == vec.end()) {
            vec.push_back(newValue);
        }
    }

    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

Explanation:

  1. Include Necessary Headers:
  2. #include <iostream>: Provides input/output stream functions.
  3. #include <vector>: Provides the vector container.
  4. #include <algorithm>: Provides algorithms for searching and sorting.

  5. Main Function:

  6. std::vector<int> vec;: Declares a vector of integers.
  7. int newValue;: Declares an integer variable to store the new input value.

  8. Insert Unique Values:

  9. while (std::cin >> newValue) { ... }: Reads input values until end-of-file or an invalid input is encountered.
  10. if (std::find(vec.begin(), vec.end(), newValue) == vec.end()) { ... }: Checks if the new value is already present in the vector.
  11. vec.push_back(newValue);: Inserts the new value into the vector if it is unique.

  12. Output Unique Values:

  13. for (int num : vec) { std::cout << num << " "; }: Prints the unique values stored in the vector.

  14. Return Statement:

  15. return 0;: Indicates successful program execution.