Sort a vector of strings

Aug 18, 2019 at 4:01am
Hi I am hoping someone might be able to help with with a quick question. I am working on a problem on paper as I am not near a computer, so I can not test what I am about to ask.

If I get input from a user as strings, and each string I pass it to a vector. Can I call sort() on the vector to put the strings into alphabetical order?
Aug 18, 2019 at 4:20am
Why wouldn't it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
   std::vector<std::string> vec = { "Can", "These", "Words", "Be", "Sorted", "?" };

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

   for (const auto& itr : vec)
   {
      std::cout << itr << "  ";
   }
   std::cout << '\n';
}
?  Be  Can  Sorted  These  Words


The wondrous things STL containers and algorithms can do.
Aug 18, 2019 at 4:43am
I've just recently became familiar with the sort function etc, so was not sure if it works the same way with strings as it does with integers. But now I know, thank you for the help
Aug 18, 2019 at 5:06am
The STL (containers, iterators, algorithms, functions) was designed to work generically on any built-in type and with any user-defined type that supports some elementary operations (such as copying and assignment).

In a rough nutshell:

While std::basic_string isn't part of the STL, it has been designed to work with the STL algorithms and functions.
Aug 18, 2019 at 5:28am
In a slightly smoother nutshell:

If it has a < operator (and is movable), you can use it with std::sort. If it doesn't have a < operator (but is still movable), then you can still use it with std::sort, but you'll need to pass it a binary predicate that it can use to sort your stuff.

-Albatross
Last edited on Aug 18, 2019 at 5:30am
Aug 18, 2019 at 7:06am
std::string is
* movable http://www.cplusplus.com/reference/string/string/operator=/
* has op< http://www.cplusplus.com/reference/string/string/operators/
Note though that the op< is case sensitive:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main() {
   std::vector<std::string> vec = { "Words", "These", "be", "sorted", "Can", "?" };
   std::sort(vec.begin(), vec.end());
   for (const auto& itr : vec) {
      std::cout << itr << "  ";
   }
   std::cout << '\n';
}

?  Can  These  Words  be  sorted  
Topic archived. No new replies allowed.