In this C++ tutorial, you shall learn how to get unique elements in a given vector using a For loop and std::count() function, with example programs.

Get Unique Elements of a Vector

To get unique elements of vector in C++, iterate over the elements of the vector from start to end, and for each element, if there is no such element in the resulting vector, add the element to the resulting vector. At the end of iteration, the resulting vector contains only the unique elements of the given vector.

Using this process, we can preserve the order of the unique elements in the vector.

C++ Program

In the following program, we take a string vector in fruits, and get the unique elements of this vector to result.

We shall use std::count() method of algorithm library to check if the current element of the iteration is in the result vector.

main.cpp

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
   vector<string> fruits { "apple", "banana", "apple", "cherry", "cherry" };
   vector<string> result;

   for( unsigned i = 0; i < fruits.size(); ++i ) {
      if ( count(result.begin(), result.end(), fruits.at(i)) == 0 ) {
         result.push_back(fruits.at(i));
      }
   }

   for(auto& element: result) {
      cout << element << "  ";
   }
}

Output

apple  banana  cherry

Conclusion

In this C++ Tutorial, we learned how to get unique elements of a vector.