Seek uniqueness? Use STL set.

8 05 2008


In several conditions we’ve to worry about avoiding duplicate data. For instance, if you have a combo-box which contains browsed file paths as history, it will be nice to avoid multiple occurrence of same file path. In those cases you can make use of STL set to remove duplicate data.


Set is a template class like any other STL container. For adding new data to set, you’ve to call insert() and for iterating you can use iterators. See sample code snippet below.

#include "set"
#include "string"
using namespace std;
...

// Set which is used to hold FilePaths as strings.
set<string> FilePathSet;

// I am inserting the same path a number of times.
// But finally, while iterating you can see only one
// copy of the same data.
FilePathSet.insert("C:\Windows\System32");
FilePathSet.insert("C:\Windows\System32");
FilePathSet.insert("C:\Windows\System32");
FilePathSet.insert("C:\Windows\System32");

// Iterate through the set.
set<string>::iterator FilePathSetItr = FilePathSet.begin();
while( FilePathSetItr != FilePathSet.end())
{
   // The unique data. Use it.
   string UniqueFilePath = *FilePathSetItr;

   // Increment to next item in set.
   ++FilePathSetItr;
}


Targeted Audience – Beginners.

Advertisements

Actions

Information

3 responses

29 12 2008
Attameceam

wkdomwwncrnuxxknwell, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch 😉

29 12 2008
Jijo.Raj

Hello Attameceam,

Welcome to WeSeeTips. So happy to know that you like it. Well, keep watching and enjoy!

Regards,
Jijo.

16 04 2009
How to Delete Duplicate entries from STL containers? « Visual C++ Tips

[…] 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 […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: