Неправильно обработан случай нескольких строк максимальной длины

Рейтинг: -2Ответов: 1Опубликовано: 27.06.2023

Задание: "В векторе строк some_vector найдите самую длинную строку и её индекс. Выведите её в соответствии с форматом выходных данных. Если несколько строк имеют одинаковую длину, выведите первую из них."

При проверке кода выводится ошибка:

"причина: Неправильный ответ

подсказка: Неправильно обработан случай нескольких строк максимальной длины."

Сам код:

    #include <iostream>
    #include <string>
    #include <vector>
    
    int main() {
        std::vector<std::string> some_vector = { "a", "b", "c", "d", "e", "f", "g" };
        int longest_index = 0;
        int current_index = 0;
        int siz = some_vector[longest_index].size();
        for (std::string el : some_vector) {
            int siz1 = el.size();
            if (siz1 > siz) {
                longest_index = current_index;
            }
            current_index += 1;
        }
        std::cout << "Longest string \"" << some_vector[longest_index] << "\" at index " << longest_index;
    }        

Подскажите, в чём именно ошибка(

При собственных проверках проблемы со строками одной длины не возникает.

UPD: проблема решена: переменную siz нужно объявлять в цикле for, чтобы siz менялась вместе с longest_index, от которой она зависима, при каждом проходе цикла.

Итоговый корректный код:

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

  int main() {
      std::vector<std::string> some_vector = { "a", "b", "c", "d", "e", "f", "g" };
      int longest_index = 0;
      int current_index = 0;
      for (std::string el : some_vector) {
          int siz = some_vector[longest_index].size();
          int siz1 = el.size();
          if (siz1 > siz) {
              longest_index = current_index;
          }
          current_index += 1;
      }
      std::cout << "Longest string \"" << some_vector[longest_index] << "\" at index " << longest_index;

Ответы

▲ 1Принят

Я бы работал через индексы, раз нужен индекс:

int main() {
    std::vector<std::string> some_vector = { "a", "b", "cc", "d", "e", "ff", "g" };
    size_t longest_index = 0, longest_size = some_vector[0].size();

    for (size_t current_index = 1; current_index < some_vector.size(); ++current_index)
        if (size_t siz; (siz = some_vector[current_index].size()) > longest_size) {
            longest_index = current_index;
            longest_size  = siz;
            }

    std::cout << "Longest string \"" << some_vector[longest_index] << "\" at index " << longest_index;
    }