How can I sort a string vector ignoring case? Like, if the input is B, c, D the result is the same and not B, D, c, which is what I get with sort(v.begin(), v.end())
Printable View
How can I sort a string vector ignoring case? Like, if the input is B, c, D the result is the same and not B, D, c, which is what I get with sort(v.begin(), v.end())
You'll have to use another form of sort() where it calls your routine, and your routine can do the case insensitive compare.
You need to pass a predicate function to sort() to ignore the case.
Here's an example from "Exceptional STL" by Scott Meyers:
Code:bool ciCharLess( char c1, char c2 )
{
return (std::tolower( static_cast<unsigned char>( c1 ) ) < std::tolower( static_cast<unsigned char>( c1 ) ));
}
bool CompareNoCase( const std::string& s1, const std::string& s2 )
{
return std::lexicographical_compare( s1.begin(), s1.end(), s2.begin(), s2.end(), ciCharLess );
}
Call the 3-argument version of sort() using a sort criterion that does what you want.
http://www.cplusplus.com/reference/algorithm/sort.html
Can you elaborate? I'm new to C++, I don't know how sort works.
Okay.
There are two types of sort:
#include <algorithm>
void sort( iterator start, iterator end );
void sort( iterator start, iterator end, StrictWeakOrdering cmp );
In a sentence, an iterator is a component of your data that can move through the range of data, and return the actual data when asked for it. In order for the sort to work, it needs to know where the range of your data begins and ends.
In the first version, sort will compare elements to eachother using the < operator, and sort the data based on that result. However in the second version, you have the option of passing along some sort of predicate that will do the same type of comparison with your data. Sometimes the predicate is just another function, and at other times it's a structure with a parens operator defined, because the programmer needs to keep track of some state, or the predicate only needs to be alive during the sort because it's only purpose is to be used by the sort, etc.