sort with char array struct

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
#include <string.h>
#include <algorithm>

using namespace std;

struct word {
	char word_arr[5];
};

bool operator < (word w1, word w2) {
	return -strcmp(w1.word_arr, w2.word_arr);
}

word words[5];

int main() {
	words[0].word_arr[0] = 'a'; words[0].word_arr[1] = '\0';
	words[1].word_arr[0] = 'b'; words[1].word_arr[1] = '\0';
	sort(words, words+2);
	printf("%s %s\n", words[0].word_arr, words[1].word_arr);
	cin.get();
	return 0;
}


This program is supposed to order the array words according to dictionary order. Why does it reorder words[0] and words[1], and print out "b a"?
Check the documentation http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
You are practically doing
1
2
3
4
//bool operator < (word w1, word w2) {
bool operator <(const word &w1, const word &w2){
	return true;
}

Last edited on
Hi,

I looked at the documentation, but I still don't understand why my operator would always return "true". I would really appreciate more explanation.
To add to ne555's hint, I'll show you something:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
    cout << (bool)  5 << endl;
    cout << (bool)  0 << endl;
    cout << (bool) -4 << endl;

    cin.get();
    return 0;
}
Got it! (bool) 5 and (bool) -4 both returns 1. Thanks, ne555 and m4ster r0shi! Everything is clear now.
Topic archived. No new replies allowed.