我目前正在阅读“使用 C++ 进行编程的原则和实践”一书。我目前有点卡在第 4 章的“试试这个”练习中。本质上,在一个 vector 中获取单词列表的练习在一个名为不喜欢的单独 vector 中有另一个单词列表,并发出不喜欢的单词的哔哔声列表。本章暗示这应该可以使用“for”函数和“while”函数来实现。我正在努力使这项工作。我在网上看到了一些解决方案,但它们使用了本书尚未涵盖的功能,我更愿意使用目前学到的功能来解决这个问题,比如嵌入东西。我是一个新手,所以非常感谢帮助。
#include "std_lib_facilities.h"
// simple dictionary: list of selected words
int main()
{
vector<string>disliked={"Brocolli","Carrots","Cabbage","Sprouts"};
vector<string>words;
for(string temp; cin>>temp;) //read whitespace separated words
words.push_back(temp); //put into vector
cout << "Number of words:" << words.size() << '\n';
sort(words); //sort the words
for (int i=0; i<words.size(); ++i)
for (int d=0; d<disliked.size(); ++d)
if (words[i]!=disliked[d])
if (i==0 || words[i-1]!=words[i])
cout << words[i] << "\n";
else
cout << "BEEP" << "\n";
}
最佳答案
我知道这是一篇旧帖子,但是如果有人想知道到目前为止书中所展示的内容的答案,请参阅下文。快乐编码!
int main()
{
vector<string> words;
vector<string> disliked = { "Broccoli", "Lettuce", "Tomato", "Pickle" };
cout << "Enter word: ";
for (string tempWord; cin >> tempWord;)
words.push_back(tempWord);
for (int i = 0; i < words.size(); ++i)
{
for (int x = 0; x < disliked.size(); ++x)
if (words[i] == disliked[x])
{
words[i] = "Bleep";
}
cout << words[i] << "\n";
}
}
关于c++ - 'Try This' vector 使示例词典中的单词发出蜂鸣声。编程原则与实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37740822/