Re: STL stable_sort sorting issue
In article <1180442852.291017.240950@k79g2000hse.googlegroups.com>,
sandy <sandip.ware@gmail.com> wrote:
Hello C++ Guru,
I am using STL stable_sort to sort the vector string data using
below code.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool my_comparison( string p1, string p2)
{
//Make first string lower case
string::iterator StringValueIterator = p1.begin();
transform (p1.begin(),p1.end(), StringValueIterator,toupper);
//Make second string lower case
StringValueIterator = p2.begin();
transform (p2.begin(),p2.end(), StringValueIterator,toupper);
return p1 < p2;
}
int main()
{
typedef vector<string> holder;
holder some_holder;
some_holder.push_back("aaa");
some_holder.push_back("bbb");
some_holder.push_back("AAA");
some_holder.push_back("BBB");
stable_sort(some_holder.begin(),some_holder.end(),my_comparison);
holder::iterator VectIt = some_holder.begin();
for( ; VectIt!=some_holder.end(); ++VectIt)
{
cout <<*VectIt<< '\n';
}
return 0;
}
I got below result :
aaa
AAA
bbb
BBB
When I am expecting result like below :.
AAA
aaa
BBB
bbb
Why it's giving preference to first small case why not upper
letter ?
Because they are put in your container first. "stable_sort" tries to
maintain the existing order of the items as best it can. Since your code
says that "aaa" and "AAA" are equal, it doesn't swap them.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]