1

I have a vector of struct items that has a string inside. I am trying to sort the vector of items by having the string inside the items in alphabetical order... so far I have:

vector<Item> sorter;

std::sort(sorter.begin(), sorter.end(), SortHelp);

//predcate function
bool SortHelp(Item const& one, Item const& two) 
{
    return one.type < two.type;
}

*type is the string that I am using to sort

How could I change the predicate function to sort the strings alphabetically?

Cœur
  • 37,241
  • 25
  • 195
  • 267
AC101
  • 13
  • 2

2 Answers2

2

The following function will do a case-insensitive compare on two std::strings without external libraries (it is C++11 though).

bool caseinsensitivecompare(string s1, string s2) {
    locale loc;
    std::transform(s1.begin(),s1.end(),s1.begin(), 
                   [loc](char c){return std::toupper<char>(c,loc);});
    std::transform(s2.begin(),s2.end(),s2.begin(), 
                   [loc](char c){return std::toupper<char>(c,loc);});
    return (s1 < s2);
}
us2012
  • 16,083
  • 3
  • 46
  • 62
0

As suggested in Case insensitive string comparison C++ (2012), strcasecmp() will provide the right answer if comparing const char * strings.

If comparing C++ strings, the Boost library has is_iless(), for which the header is here, as suggested by Case insensitive string comparison in C++ (2008).

Community
  • 1
  • 1
Simon
  • 10,679
  • 1
  • 30
  • 44
  • yea it was changed from strings to char[16] and sample output is: Ingredient, weapon, armor, weapon... how could i compare the char array then to see which is supposed to be where? – AC101 Feb 10 '13 at 02:44
  • @AC101 What is it that's unclear to you? Use `strcasecmp()`, just like Simon said (documentation either via google or on linux via `man 3 strcasecmp`). – us2012 Feb 10 '13 at 03:22