[решено] Не работает код, что вычисляет длинные слова
проблема такая: уникальные слова вычисляются отлично, но вот переменная 'longest_word' будто сбрасывается при итерации вложенного цикла, хотя объявлена в основном. в коде есть мои комментарии, это поможет легче разобраться. код:
12345678910111213141516171819202122232425262728293031
size_t start_pos = 0, end_pos = 0, sentence_counter = 0;
while ((start_pos = str.find_first_not_of(end_symbols, end_pos)) != std::string::npos) {
end_pos = str.find_first_of(end_symbols + ' ', 1 + start_pos); // ищем конец слова/предложения со стартовой позиции
if (end_pos == std::string::npos) end_pos = str.size(); // если в конце предложения не стоял разделитель то сами присваиваем
std::string longest_word; // объявляем переменную для самого длинного слова
std::string sentence = str.substr(start_pos, end_pos - start_pos); // выделяем текущее предложение
size_t sen_start = 0, sen_end = 0; // переменные для начала/конца
while ((sen_start = sentence.find_first_not_of(' ', sen_end)) != std::string::npos) {
sen_end = sentence.find(' ', sen_start);
if (sen_end == std::string::npos) sen_end = sentence.size(); // если конец предложения и не заканчивается точкой
std::string word = sentence.substr(sen_start, sen_end - sen_start);
if (word.size() > longest_word.size()) longest_word = word;
// добавляем новое слово (только если уникальное)
auto it = std::find_if(unique_words.begin(), unique_words.end(), [&word](const std::string& current) {
return current == word;
});
if (it == unique_words.end()) unique_words.push_back(word);
}
sentence_counter++;
longest_words.push_back(longest_word);
}
p.s. решил удалением пробела из аргументов в строке:
1234
end_pos = str.find_first_of(end_symbols + ' ', 1 + start_pos);
нужно было поменять на:
end_pos = str.find_first_of(end_symbols, 1 + start_pos);
По дате
По рейтингу
1234567891011121314151617181920212223242526272829303132333435363738394041
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
vector<string> longest_words(const string& words) {
stringstream ss(words);
string word;
unordered_set<string> set_words;
while (ss >> word) {
set_words.insert(word);
}
vector<string> tmp(begin(set_words), end(set_words));
auto cmp = [](const string& a, const string& b) {
return a.length() > b.length();
};
sort(begin(tmp), end(tmp), cmp);
const auto length = begin(tmp)->length();
vector<string> result;
for (const auto& item : tmp) {
if (item.length() == length) {
result.push_back(item);
}
}
sort(begin(result), end(result));
return result;
}
int main() {
cout << ">>> ";
string words;
getline(cin, words);
const auto result = longest_words(words);
for (const auto& word : result) {
cout << "<<< " << word << '\n';
}
}
Больше по теме