sorting a vector of classes containing strings

The title says it all. Like in this example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector<string> Words;

    Words.push_back("Apple");
    Words.push_back("Villain");
    Words.push_back("Person");

    sort(Words.begin(), Words.end());

    for(int i = 0; i < (int)Words.size(); i++)
    {
        cout << Words[i].Word << endl;
    }

    return 0;
}

The above sorts a vector of strings and works fine.
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
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class Stuff
{
    public:

    string Word;
    int num;
    int num2;
};

int main()
{
    vector<Stuff> Words;

    Words.resize(Words.size() + 3);

    Words[0].Word = "Apple";
    Words[1].Word = "Villain";
    Words[2].Word = "Person";

    sort();

    for(int i = 0; i < (int)Words.size(); i++)
    {
        cout << Words[i].Word << endl;
    }

    return 0;
}

But what about this? theres different values in the class and if I try Words.Word.begin() that doesn't work because i need to sort the strings in each class. Any ideas?
Last edited on
if you want to sort complex data like that 'Stuff' use the operator<() like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Stuff
{
    public:

      bool operator<(const Stuff &s) const
      {
        return (Word < s.Word) && (num < s.num) ...;
      }

    string Word;
    int num;
    int num2;
};
Topic archived. No new replies allowed.