Set container dose not sort string array elements correctly

Viewed 52

I'm wondering why the below set container code can't sort array of string?

Result sequence of below code is {"B","A","C"} as the sequence of input and I hope to see either {"A","B","C"} or {"C","B","A"} instead.

#include<fstream>
#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include <set>

using namespace std;


int main()
{
        std::set<char*> cell_name;
        cell_name.clear();
        cell_name = {"B","A","C"};


        std::set <char*>::iterator iter;

        for (iter = cell_name.begin();iter!=cell_name.end();++iter)
            cout << ' ' << *iter;
        cout << '\n';

    return 0;
}
1 Answers

The std::set orders the elements by their value, and in your case the element is the pointer. You have two options:

  • Remake pointer to std::string
#include<fstream>
#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include <set>


int main()
{
        std::set<std::string> cell_name;
        cell_name.clear();
        cell_name = {"B","A","C"};


        std::set <std::string>::iterator iter;

        for (iter = cell_name.begin();iter!=cell_name.end();++iter)
            std::cout << ' ' << *iter;
        std::cout << '\n';

    return 0;
}
  • Provide a custom comparator to take pointer into account:
#include<fstream>
#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include <set>

struct StrComparator
{
  bool operator()(const char *s1, const char *s2) const
  {
    return strcmp(s1, s2) < 0;
  }
};

int main()
{
        std::set<const char*, StrComparator> cell_name;
        cell_name.clear();
        cell_name = {"B","A","C"};


        std::set <const char*>::iterator iter;

        for (iter = cell_name.begin();iter!=cell_name.end();++iter)
            std::cout << ' ' << *iter;
        std::cout << '\n';

    return 0;
}
Related