How to Delete Duplicate entries from STL containers?

16 04 2009


If you want to remove duplicate items, you can go for stl::set. But what to do if you want to delete duplicate data from other containers?

removeduplicate
Picture Courtesy – Squidoo


You can use std::unique() algorithm to remove adjacent duplicate items. So at first, sort your data, then call std::unique(). Now all the duplicate data will be rearranged to end of container. Now delete the unwanted range of duplicate data. Have a look at code snippet below.

#include <vector>
#include <string>
#include <algorithm>

using namespace std;

int main(int argc, char* argv[])
{
    // Election list.
    vector<string> ElectionList;
    ElectionList.push_back( "Sam" );
    ElectionList.push_back( "John" );
    ElectionList.push_back( "Ron" );
    ElectionList.push_back( "Sam" );
    ElectionList.push_back( "John" );

    // Sort the list to make same items be together.
    sort( ElectionList.begin(), ElectionList.end());

    // Rearrange unique items to front.
    vector<string>::iterator Itr = unique(
        ElectionList.begin(),
        ElectionList.end());

    // Delete the duplicate range.
    ElectionList.erase( Itr, ElectionList.end());
}


Take care that std::unique() just removes the adjacent duplicate entries. It wont remove the entire duplicate entries present in the container. That’s why we need to sort the container at first, which will arrange all duplicate entries to adjacent  locations. 😉


Targeted Audience – Beginners.





How to sort an array by using STL?

10 08 2008

Today I’ll tell a story… Its interesting!

Once upon a time, there lived a C++ Padawan. One day, he want to sort an array. He knows that STL have std::sort() function. But he want to sort an array, not an STL container. What a fool he is? Native array’s don’t have iterators. So how could he call the std::sort() function? Well, he is clever – he created a vector, copied his array to vector, then he called the sort() function. After sorting, he copied the data back to array.

The End!

But now he is ashamed of what he did. Because now he realize that he can use std::sort() directly on native array too! But how?


You can use array pointers direclty in STL algorithms. They act like iterators itself. Have a look at the code snippet.

// Integer array with 10 items.
int Array[10] = { 9,3,2,4,0,6,7,8,1,5 };

// Sort them.
std::sort( Array, Array + 10 );


Well, Can you guess – who was that C++ trainee? It was me. 😉


Targeted Audience – Beginners.