C++ Notes: Example - Words in Reverse Order - vector

  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 
// arrayptr/reverse-word-order-vector.cpp - Reverse words using vector.
// Fred Swartz - 2004-02-02

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>  // For reverse
using namespace std;

//======================================================= main
int main() {
    vector<string> words;
    string aWord;
    
    //-- Read into the vector
    while (cin >> aWord) {
        words.push_back(aWord);
    }
    
    //--- Reverse the vector
    reverse(words.begin(), words.end());
    
    //--- Print the vector
    for (int i=0; i<words.size(); i++) {
        cout << words[i] << endl;
    }
    
    system("PAUSE"); // NON-PORTABLE. Keep Dev-C++ window open.
}