Sorting a Range of elements that you need to sort. - C++ STL Algorithm

C++ examples for STL Algorithm:sort

Description

Sorting a Range of elements that you need to sort.

Demo Code

#include <iostream>
#include <istream>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;
template<typename C>
void printContainer(const C& c, char delim = ',', ostream& out = cout) {
   printRange(c.begin(), c.end(), delim, out);
}

template<typename Fwd>
void printRange(Fwd first, Fwd last, char delim = ',', ostream& out = cout) {
   out << "{";
   while (first != last) {
      out << *first;/*from   ww  w . j a v a2s  . co  m*/
      if (++first != last)
         out << delim << ' ';
   }
   out << "}" << endl;
}

int main() {

   cout << "Enter a series of strings: ";

   istream_iterator<string> start(cin);
   istream_iterator<string> end; // This creates a "marker"
   vector<string> v(start, end);

   sort(v.begin(), v.end());
   printContainer(v);

   random_shuffle(v.begin(), v.end()); // See 7.2

   string* arr = new string[v.size()];

   copy(v.begin(), v.end(), &arr[0]);

   sort(&arr[0], &arr[v.size()]);
   printRange(&arr[0], &arr[v.size()]);

   // Create a list with the same elements
   list<string> lst(v.begin(), v.end());

   lst.sort();

   printContainer(lst);
}

Result


Related Tutorials