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:
- Include Necessary Headers:
#include <iostream>
: Provides input/output stream functions.#include <vector>
: Provides the vector container.#include <algorithm>
: Provides algorithms for searching and sorting.Main Function:
std::vector<int> vec;
: Declares a vector of integers.int newValue;
: Declares an integer variable to store the new input value.Insert Unique Values:
while (std::cin >> newValue) { ... }
: Reads input values until end-of-file or an invalid input is encountered.if (std::find(vec.begin(), vec.end(), newValue) == vec.end()) { ... }
: Checks if the new value is already present in the vector.vec.push_back(newValue);
: Inserts the new value into the vector if it is unique.Output Unique Values:
for (int num : vec) { std::cout << num << " "; }
: Prints the unique values stored in the vector.Return Statement:
return 0;
: Indicates successful program execution.