[cs13001] Sort function and strings

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Nov 14 17:00:19 EST 2012


> In class today you were showing an example code of vectors and
> specifically showed us this code: sort(v.begin(), v.end());. Would
> this function sort a vector of type string? I assume if it did so,
> that it would be sorted alphabetically as well.

Yes, strings can be sorted as well. The below code:
-------------------
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main(){
  string hw="Hello World!";
  sort(hw.begin(), hw.end());
  cout << hw << endl;
}
--------

Outputs:

 !HWdellloor

Note that to invoke sort() function you need to include <algorithim>
header.

Thanks,
-- 
Mikhail


More information about the cs13001 mailing list