Sorting a vector of words alphabetically?

Hi

I have a program in which I read (using ifstream) words from a file into a vector word objects - The word is stored (as a string) as well as a few other attributes about the word in the file.
Could someone point me in the right direction of how to sort this vector by the word names alphabetically?

I've seen the equivalent done with arrays when using the algorithm package and the sort function. Is this possible using vectors as I've described?

Thanks for any help.
Could you be more specific about what you are storing? That way we not only point you in the right direction but also validate your design, as well.

For example, if you only wanted a sorted list of strings (words), you could just put them in a set<string> which would be sorted automatically.

Another example would be if you wanted to count the number of words in a file by storing a string and a single attribute (count), you could use a map.

From what you described it sounds like you could have a Word class that defines the < operator (so that STL containers can use it to sort items) and store those in a set<Word>. Here's a sloppy attempt to do this:

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
36
37
38
39
40
41
42
#include <iostream>
#include <set>

using namespace std;

class Word
{
    string _word;
    int _count;
    int _color;
    bool _bold;
public:
    Word( string word ): _word( word ) {}

    string getWord() const { return _word; }
    
    friend bool operator<( const Word &lhs, const Word & rhs )
    {
        return lhs._word < rhs._word;
    }
};

int main( int argc, char * args[] )
{
    set<Word> words;

    Word pimp( "pimp" );
    Word apple( "apple" );
    Word box( "box" );

    // sorts upon insertion 
    words.insert( pimp );
    words.insert( box );
    words.insert( apple );

    for( set<Word>::const_iterator i = words.begin(); i != words.end(); ++i )
    {
        cout << (*i).getWord() << endl;
    }

    return 0;
}
Topic archived. No new replies allowed.