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;
}
  1. Include Necessary Libraries:
  2. #include <iostream>: Includes the input/output stream library.
  3. #include <vector>: Includes the vector library.
  4. #include <algorithm>: Includes the algorithm library.

  5. Define the Main Function:

  6. int main() { ... }: Entry point of the program.

  7. Create a Vector:

  8. std::vector<int> vec = {1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5};: Initializes a vector with duplicate elements.

  9. Use std::unique and vec.erase:

  10. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());: Removes adjacent duplicates from the vector.

  11. Output the Modified Vector:

  12. for (int i : vec) { std::cout << i << " "; }: Prints the elements of the modified vector.

  13. Return 0:

  14. return 0;: Indicates successful program execution.