-3

I am trying to sort an array of strings. I was doing some tests and I found something that I did not expect. I can not explain it.

if ("test" < "paul")
{
  cout << "test is less than paul" << endl;
}

Why is "test" less than "paul"? 'p' has a lower ASCII value than 't'. It also comes before p in the alphabet. The string length is also the same in both cases.

I am using swap() to sort the array in alphabetical order(well trying to). I can not use sort(), I need to use swap.

update: in the above example I used a pointer, but this is my actual code.

DynamicArray<string> sectionName;  //declaration
swap(alreadySeen[i].sectionName[j],alreadySeen[i].sectionName[i]); //usage

This is obviously not the complete code, don't want to get lost in the details

asmcriminal
  • 93
  • 12

1 Answers1

1

Always compile with warnings enabled.

 warning: comparison with string literal results in unspecified behavior [-Waddress]
     if ("test" < "paul")
                  ^~~~~~

You are not comparing strings, you are comparing memory addresses. Here's a wandbox example.

In order to achieve what you want:

  • If you need to use C-style strings, use std::strcmp:

    if(std::strcmp("test", "paul") < 0) { /* ... */ }
    
  • If you can use std::string, you can simply write:

    if(std::string{"test"} < std::string{"paul"}) { /* ... */ }
    
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • using std::string seems excessive to me. But there is an interesting potential bonus: Are strings locale sensitive? Comparisons between *words* (semantically) generally may depend on locale. – Peter - Reinstate Monica Oct 06 '16 at 08:25
  • Thanks I like your answer. I updated my code, I used strings not pointers. I guess I just used the pointers for the example. – asmcriminal Oct 06 '16 at 08:32
  • @VittorioRomeo I originally did it the way you said and it produces that error. – asmcriminal Oct 06 '16 at 08:36
  • @VittorioRomeo Nevermind, I guess my sorting loops are messed up. If I do "string test = "test"; string paul = "paul" it does work how you say. – asmcriminal Oct 06 '16 at 08:39