C++: Containers: Example 1 Using a Vector
One of three contrasting examples of solving the problem with increasingly
powerful tools:
using arrays, then
vectors, then
stacks.
The great advantage of using vectors and strings instead of
arrays is that there are no size limits - strings and vectors expand
as needed.
// Read words and print them in reverse order.
// Variation 3: Using vector and string
// Fred Swartz 2001-11-08, 2001-12-04
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> allwords; // vector of strings to hold words
string word; // input buffer for each word.
//--- read words/tokens from input stream
while (cin >> word) {
allwords.push_back(word);
}
int n = allwords.size();
cout << "Number of words = " << n << endl;
//--- write out all the words in reverse order.
for (int i=n-1; i>=0; i--) {
cout << allwords[i] << endl;
}
return 0;
}//end main