https://rentry.org/PPP2_p123

// Code derived from Stroustrup's PPP2 book
// § 4.6.4 A text example
//  -and beginning on p 123

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::string;
using std::vector;

template <typename C>
void sort(C& c)
{
  std::sort(begin(c), end(c));
}

// simple dictionary: list of sorted words
int main()
{
  cout << "Please enter words: ";  // note: see input stream comments on p 124
                                   //  (ie, use ctrl+d to end input of strings)
  vector<string> words;
  for (string temp; cin >> temp;)  // read whitespace-separated words
    words.push_back(temp);         // put into vector

  cout << "Number of words: " << words.size() << '\n';

  sort(words);  // sort the words

  for (unsigned int i = 0; i < words.size(); ++i)
    if (i == 0 || words[i - 1] != words[i])  // is this a new word?
      cout << words[i] << '\n';
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_04/main_p123.cpp && ./a.out

PrevUp

Edit
Pub: 08 Feb 2023 02:48 UTC
Edit: 29 Apr 2023 08:48 UTC
Views: 452