Хорошо, позвольте мне объяснить простой подход к этому. Есть и более элегантные, но сейчас важно, чтобы вы почувствовали, как получить доступ к std::vector
и как правильно составить управляющие структуры.
Шаг 1 - цикл по всем элементам вектора
Вы можете использовать итераторы для прохождения всех элементов вектора.
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
// now *it gives access to the current element (here: current dislike word)
if (*it == words) {
// ... yeah, we found out the current word is on the list!
}
}
Вы получаете итератор для первого элемента вектора, вызывая begin()
, затем продолжаете увеличивать (++it
) его, пока не достигнете конца вектора. Я использую const_iterator
здесь, потому что я не собираюсь изменять какие-либо элементы, если вам нужно, используйте iterator
.
с std::vector
, индексация с помощью [index]
также возможна (но обычно не рекомендуется):
for(size_t i = 0;i < dislike.size(); ++i) {
// dislike[i] is the current element
if (dislike[i] == words) {
// huuuuray! another BEEEP candidate
}
}
Шаг 2 - разорвать петлю рано
Как только вы точно знаете, что у нас есть слово неприязни, вам больше не нужно искать вектор.
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
if (*it == words) {
// we found a positive match, so beep and get out of here
cout << "Bleep!" << endl;
break;
}
}
Шаг 3 - запишите, если мы уже обработали слово
bool is_beep = false;
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
if (*it == words) {
// we found a positive match, so beep and get out of here
cout << "Bleep!" << endl;
is_beep = true;
break;
}
}
// this is not a dislike word if is_beep is false, so print it as usual
if (!is_beep) {
cout << words << endl;
}
Шаг 4 - собрать все вместе
int main()
{
vector<string>dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
string words = " ";
cout << "Please enter some words: " << endl;
while(cin>>words)
{
bool is_beep = false;
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
if (*it == words) {
// we found a positive match, so beep and get out of here
cout << "Bleep!" << endl;
is_beep = true;
break;
}
}
// this is not a dislike word if is_beep is false, so print it as usual
if (!is_beep) {
cout << words << endl;
}
}
system("pause");
return 0;
}
Проверьте std::find
для более идиоматического решения - оно в основном спасает вас от внутреннего цикла. Вы также можете избавиться от этого bool
в последнем примере кода, если немного реструктурировать. Я оставлю это вам в качестве упражнения (подсказка: оставьте итератор живым и проверьте его значение после завершения цикла).