Advertisement
janac

Find longest word

Nov 4th, 2021 (edited)
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5.  
  6. // Take a list of words and return the longest word.
  7. string get_longest_word(vector<string>& word_list)
  8. {
  9.     // This will store the longest word.
  10.     string longest_word;
  11.  
  12.     // We are testing this word.
  13.     string current_word;
  14.  
  15.     // Start with zero as the greatest length.
  16.     int greatest_length = 0;
  17.  
  18.     // This is the length of the current word.
  19.     int length = 0;
  20.  
  21.     // Go from the beginning to the end of the word list.
  22.     for (size_t i = 0; i < word_list.size(); ++i)
  23.     {
  24.         // Get the next word.
  25.         current_word = word_list[i];
  26.  
  27.         // Let the length of the next word.
  28.         length = current_word.size();
  29.  
  30.         // If the length is the longest so far,
  31.         if (length > greatest_length)
  32.         {
  33.             // Store the new greatest length.
  34.             greatest_length = length;
  35.  
  36.             // Store the word with the greatest length.
  37.             longest_word = current_word;
  38.         }
  39.     }
  40.  
  41.     return longest_word;
  42. }
  43.  
  44. int main()
  45. {
  46.     // Create a list of words.
  47.     vector<string> words = { "red", "blue", "yellow", "pink" };
  48.  
  49.     // Get the longest word.
  50.     string longest = get_longest_word(words);
  51.  
  52.     // Display the longest word.
  53.     cout << longest << endl;
  54.  
  55.     return 0;
  56. }
  57.  
  58.  
  59.  
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement