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 Change the Icon of MFC application?

5 04 2009


When you create an MFC application, did you notice the icon of executable? Yes! its that same old icon. But I’ve seen other application with different icon. Well, how to set the icon of executable to give a new face for it? 😉

setappicon
Image Courtesy – Flickr


The secret is, windows will choose the first icon present in executable as exe icon. By default for an MFC application, IDR_MAINFRAME will be the icon resource name and it have the lowest resource value – 128. Follow the steps to add an icon and make set it the first one in executable.

1. Import a new icon by using resource editor.

setappicon1

2. Let the icon be IDR_ICON1.
3. Now open resource.h and you can see, IDR_MAINFRAME which is the mfc icon, have lowest resource id.

setappicon2
4. Now edit the resource.h to make IDI_ICON1 as lowest resource id.

setappicon3
5. Now clean and build your application and check the application icon. Wow! its changed!!!


The point is, the icon should be the first icon in executable. You can set icon value even to zero. It will work!


Targeted Audiance – Intermediate.