vector unique in c++
Using the std::unique
Function in C++ to Remove Adjacent Duplicates in a Vector
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5};
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
for (int i : vec) {
std::cout << i << " ";
}
return 0;
}
- Include Necessary Libraries:
#include <iostream>
: Includes the input/output stream library.#include <vector>
: Includes the vector library.#include <algorithm>
: Includes the algorithm library.Define the Main Function:
int main() { ... }
: Entry point of the program.Create a Vector:
std::vector<int> vec = {1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5};
: Initializes a vector with duplicate elements.Use
std::unique
andvec.erase
:vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
: Removes adjacent duplicates from the vector.Output the Modified Vector:
for (int i : vec) { std::cout << i << " "; }
: Prints the elements of the modified vector.Return 0:
return 0;
: Indicates successful program execution.