Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <string>
- using namespace std;
- // Take a list of words and return the longest word.
- string get_longest_word(vector<string>& word_list)
- {
- // This will store the longest word.
- string longest_word;
- // We are testing this word.
- string current_word;
- // Start with zero as the greatest length.
- int greatest_length = 0;
- // This is the length of the current word.
- int length = 0;
- // Go from the beginning to the end of the word list.
- for (size_t i = 0; i < word_list.size(); ++i)
- {
- // Get the next word.
- current_word = word_list[i];
- // Let the length of the next word.
- length = current_word.size();
- // If the length is the longest so far,
- if (length > greatest_length)
- {
- // Store the new greatest length.
- greatest_length = length;
- // Store the word with the greatest length.
- longest_word = current_word;
- }
- }
- return longest_word;
- }
- int main()
- {
- // Create a list of words.
- vector<string> words = { "red", "blue", "yellow", "pink" };
- // Get the longest word.
- string longest = get_longest_word(words);
- // Display the longest word.
- cout << longest << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement