sorting vector

closed account (oLC9216C)
Hi, I want to sort a vector<string> list alphabetically.
How can I do that?

for example I have a vector<string> with:
apple
alike
add
cat
blue
red
lion

how can I make it become

add
alike
apple
blue
cat
lion
red

The string value is only a word not a sentence.
The simplest way is to use std::sort() from the algorithm library.

http://www.cplusplus.com/reference/algorithm/sort/

1
2
3
4
5
6
7
8
9
#include <algorithm>

// ...

std::vector<std::string> vs; // assume it contains words

// ...

std::sort(vs.begin(), vs.end());


You shouldn't name your vector as "list" because there might be confusion between that and std::list, which is another container just like std::vector.

http://www.cplusplus.com/reference/stl/

If you want to do the sorting yourself, read more here:

http://www.cplusplus.com/faq/sequences/sequencing/sort-stuff/
http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/
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
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector<string> vs;
    vs.push_back("apple");
    vs.push_back("alike");
    vs.push_back("add");
    vs.push_back("cat");
    vs.push_back("blue");
    vs.push_back("red");
    vs.push_back("lion");

    for (vector<string>::iterator it = vs.begin() ; it != vs.end(); ++it)
        cout << ' ' << *it;
    
    sort(vs.begin(),vs.end());
    
    cout << "\n";
    
     for (vector<string>::iterator it = vs.begin() ; it != vs.end(); ++it)
        cout << ' ' << *it;
    
    
   
   return 0;
}
Last edited on
Topic archived. No new replies allowed.