Advertisement
RobertDeMilo

YB1.6 Возврат нескольких значений из функции

Oct 27th, 2023
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <tuple>
  4. #include <utility>
  5. #include <map>
  6. #include <set>
  7.  
  8. using namespace std;
  9.  
  10. class Cities
  11. {
  12. public:
  13.     tuple<bool, string> FindCountry(const string& city) const
  14.     {
  15.         // Метод константный. У класса есть поле со словарем, а [] для словаря теоретически могут
  16.         // менять сам словарь добавляя в него элементы, если их там нет
  17.         // Поэтому нужно обратиться к ключу КОНСТАНТНОГО словаря
  18.  
  19.         if (city_to_country.count(city) == 1)
  20.         {
  21.             //return { true, city_to_country[city] };
  22.             // at - если ключ не нашелся, то он его не добавит, а выбросит исключение  
  23.             return { true, city_to_country.at(city) };
  24.         }
  25.         else if (ambigious_cities.count(city) == 1)
  26.         {
  27.             return { false, "Ambigious" };
  28.         }
  29.         else
  30.         {
  31.             return { false, "Not exist" };
  32.         }
  33.     }
  34.    
  35. private:
  36.     map<string, string> city_to_country; // по названию города хранит название страны
  37.     set<string> ambigious_cities;
  38. };
  39.  
  40. int main()
  41. {
  42.     Cities cities;
  43.  
  44.     /*bool success;
  45.     string message;*/
  46.  
  47.     /*auto t = cities.FindCountry("Volgograd");
  48.     cout << get<1>(t) << endl;*/
  49.     /*tie(success,message) = cities.FindCountry("Volgograd");
  50.     cout << success << " " << message << endl;*/
  51.  
  52.     auto [success, message] = cities.FindCountry("Volgograd");
  53.     cout << success << " " << message << endl;
  54.  
  55.     map<string, pair<double, double>> citiess;
  56.  
  57.     for (const auto& item : citiess)
  58.     {
  59.         cout << item.second.first << endl;
  60.     }
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement