Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Osman Zakir
- // 5/11/2015
- // Programming: Principles and Practice Using C++ Second Edition Chapter 8 Exercises
- // This program is supposed to find and print the longest and shortest string in a vector of strings
- // Find and print the lexicographically first and last string
- // And is also supposed to be able to find and print the lengths of each of the strings inside the vector
- #include "../custom_std_lib_facilities.h"
- #include <algorithm>
- #include <string>
- #include <vector>
- #include <limits>
- using namespace std;
- vector<string> get_input();
- void print_size(const vector<int>& sizes);
- vector<int> string_size(const vector<string>& words);
- void print_first_last(vector<string>& words);
- string longest_string(const vector<string>& words);
- string shortest_string(const vector<string>& words);
- void print_longest_shortest(const string& shortest, const string& longest);
- int main()
- {
- vector<string> words = get_input();
- vector<int> string_length = string_size(words);
- string shortest = shortest_string(words);
- cout << "\n";
- string longest = longest_string(words);
- cout << "\n";
- print_longest_shortest(shortest, longest);
- cout << "\n";
- print_first_last(words);
- cout << "\n";
- print_size(string_length);
- cout << "\n";
- keep_window_open();
- }
- vector<string> get_input()
- {
- string word;
- vector<string> words;
- cout << "Enter some words; enter CTRL+Z to stop.\n";
- while (cin >> word)
- {
- words.push_back(word);
- }
- return words;
- }
- vector<int> string_size(const vector<string>& words)
- {
- vector<int> sizes;
- for (auto const& x : words)
- {
- sizes.push_back(x.length());
- }
- return sizes;
- }
- void print_size(const vector<int>& sizes)
- {
- cout << "The sizes are:\n";
- for (auto const& x : sizes)
- {
- cout << x << "\n";
- }
- }
- string shortest_string(const vector<string>& words)
- {
- string shortest = words[0];
- for (auto const& x : words)
- {
- if (x.length() < shortest.length())
- {
- shortest = x;
- }
- }
- return shortest;
- }
- string longest_string(const vector<string>& words)
- {
- string longest = std::numeric_limits<string>::lowest();
- for (auto const& x : words)
- {
- if (x.length() > longest.length())
- {
- longest = x;
- }
- }
- return longest;
- }
- void print_longest_shortest(const string& shortest, const string& longest)
- {
- cout << "The longest word is: \'" << longest << "\' and the shortest word is: \'" << shortest << "\'\n";
- }
- void print_first_last(vector<string>& words)
- {
- sort(words.begin(), words.end());
- cout << "Lexicographically, the first element is: \'" << words.front() << "\' and the last one is: \'" << words.back() << "\'\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement