|
Question : STL: Removing dublicates from the list of strings
|
|
Hi,
How do i remove dublicates from my list of strings:
typedef std::list list_string; ................................ ............................... list_string Check_string;
Thank you
|
|
Answer : STL: Removing dublicates from the list of strings
|
|
No, tha was my fault - it should be
for ( i = rlst.begin(); i != rlst.end (); ++i) {
for ( j = rlst.begin(); j != rlst.end (); ++j) {
if ( *j == *i && j != i) rlst.erase(j++); // increment was missing } }
Or, in your case:
list_string Check_string;
for (std::list::iterator i= Check_string.begin();i!=Check_string.end();i++) {
for (std::list::iterator j = Check_string.begin();j!=Check_string.end();j++) {
if ( *j == *i && j != i) Check_string.erase(j++); } }
Here's a complete sample app:
#include #include #include using namespace std;
void remove_duplicates ( list& rlst) {
list::iterator i; list::iterator j;
for ( i = rlst.begin(); i != rlst.end (); ++i) {
cout << "Checking " << *i << endl;
for ( j = rlst.begin(); j != rlst.end (); ++j) {
cout << "...testing " << *j << endl; if ( *j == *i && i != j) rlst.erase(j++); } } }
void main () {
list lst;
lst.push_back("aaa"); lst.push_back("bbb"); lst.push_back("ccc"); lst.push_back("aaa"); lst.push_back("ddd"); lst.push_back("bbb");
remove_duplicates ( lst);
list::iterator i;
for ( i = lst.begin(); i != lst.end(); ++i) cout << *i << endl; }
|
|
|