Skip to main content

Exercise 6.2: sort-strings-2.0.cpp

//sort_strings-2.0.cpp
//Alternative solution to Exercise 6.2
//using the STL sort function with iterators
//This is quite advanced, but is a more standard
//way of solving the problem.

//Reads in words from the console into a
//vector of string variables, then outputs the
//words in dictionary order to the console.

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> //provides STL sort function
using namespace std;

typedef vector<string> strvec;

int main()
{
  strvec sv; //empty vector of strings to store words
  string sorted; //empty string of sorted words
  //get words from input
  cout << "Enter the words for sorting, end with ' ! ':" 
       << endl;
  while (true)
    {
      string word;
      cin >> word;
      if (word == "!") break;
      sv.push_back(word);
    }

  //sort words - use STL function with iterators
  sort(sv.begin(), sv.end());

  //concatenate into one string use iterators
  for (int w = 0; w < sv.size(); w++)
    {
      sorted = sorted + sv[w] + "\n";
    }
      
  //output sorted string to console
  cout << endl << sorted;
  
  system("PAUSE");
  return(0);
}