使用向量来淹没一些预定义的字符串

时间:2011-04-28 16:37:59

标签: c++ vector

所以我现在在Bjarne Stroustrup的编程手册“编程:使用c ++的原理和实践”中进行练习,而且我还是坚持不懈地努力。基本上,练习是编写一个程序,剔除它不喜欢的单词。它的工作方式是用户输入一个字符串,程序重复该单词。如果用户输入的单词是不喜欢向量的一部分,则该单词将被“Bleep”替换。 (我不知道我是否解释了这一点,但理解这一点并不复杂。)

这是我的程序版本:

int main()
{
    string dislike = "Potato";
    string words = " ";

    cout << "Please enter some words: " << endl;
    while(cin>>words)
    {
        if(words==dislike)
        {
            cout << "Bleep!" << endl;
        }

        else
        {
            cout << words << endl;
        }
    }
    system("pause");
    return 0;
}

正如你所看到的,这个版本没有使用向量(它应该,因为在本章的向量解释之后,运动是正确的)。所以我的问题是,如何在其中实现一个包含许多“不喜欢”单词的向量:

vector<string>dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");

并使它像我的其他版本没有向量一样工作(重复单词,但是不喜欢这些不喜欢的单词)。我似乎无法理解如何在向量中导航,以便它只会使“不喜欢”的单词黯然失色。

如果有人能帮助我并向我解释它是如何运作的(请不要只给我答案),我们将非常感激。

感谢您的时间和帮助,单独学习c ++并不总是很简单,我感谢这个网站让我的学习曲线更容易。

bobicool

9 个答案:

答案 0 :(得分:4)

好的,让我解释一下它的简单方法。有更多优雅的,但是现在重要的是你要了解如何访问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。我将把它作为练习留给你(提示:保持迭代器活着并在终止循环后检查它的值)。

答案 1 :(得分:0)

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)
    {
        if(find(dislike.begin(), dislike.end(), words) != dislike.end())
        {
            cout << "Bleep!" << endl;
        }

        else
        {
            cout << words << endl;
        }
    }
    system("pause");
    return 0;
}

std::find为您的来源添加#include <algorithm>

答案 2 :(得分:0)

使用std :: find(your_vector.begin(),your_vector.end(),words)

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)
    {
        if(std::find(dislike.begin(), dislike.end(), words) != dislike.end())
        {
            cout << "Bleep!" << endl;
        }

        else
        {
            cout << words << endl;
        }
    }
    system("pause");
    return 0;
}

答案 3 :(得分:0)

以下是我在阅读时对书中特定问题的解决方案。 :)希望它不言自明。

/*THE QUESTION GOES LIKE;
Write a program that “bleeps” out words that you don’t like; that is, you read in words    
using cin and print them again on cout. If a word is among a few you have defined, you
write out BLEEP instead of that word. Start with one “disliked word” such as string
disliked = “Broccoli”; 
When that works, add a few more.*/



#include "std_lib_facilities.h"  // this is a standard library header that came with 
the book

int main () {
vector<string> dislike = {"Dislike", "Alike", "Hello", "Water"};   /* defining a vector  
for the disliked words. */

vector<string> words;  //initializing vector for the read words.

cout << "Please enter some words\n";   //prompt user to enter some words.

for( string word; cin >> word;)  //this current word typed is read in.

    words.push_back(word);   // word read in are pushed into the vector "words".

sort(words);  /* function for the standard library for sorting data...this makes the data from the vector "words" appears in alphabetical order. */

for (int i=0; i<words.size(); ++i){   /*this acts as an iterator. and goes through all the element of the vector "words".  */

    if(i==0 || words[i-1]!=words[i]){   /*this prevents the words from repeating....just an option incase the user enters same kinda words twice or more. */

        if(words[i]!=dislike[0] && words[i]!=dislike[1] && words[i]!=dislike[2] && words[i]!=dislike[3])  /*This test checks whether the words typed match any of the elements of the vector "dislike".if they don't match;   */

            cout << words[i]<< '\n';  //prints out the words.
        else
            cout << "BlEEP!\n";   //if they match....print out "BlEEP!".
       }
   }


}

答案 4 :(得分:0)

我正在学习C ++。该计划已被更改一些。 写一个&#34;哔哔&#34;说出你不喜欢的坏词;那是, 你用cin阅读单词并在cout上再次打印它们。如果一个单词是你定义的几个单词之一,你就写出BLEEP和/或让它BLEEP(声音)而不是那个单词。从一个&#34;坏词开始#34;例如 - string badword =&#34; ass&#34 ;;当它工作时,添加一些或根据你不想打印的所有坏词写一个完整的程序。

while (cin >> words)
{
    if(find(badwords.begin(), badwords.end(),words) !=badwords.end())
    {
        cout << "      " << endl; // You can put Bleep in or leave it out (Blank) if blank
                                  // it will leave a blank in the phrase when it prints
        Beep(523,500);            // This is to Bleep (Sound) when a bad word is found
        cin.get();                
    }
    else
    {
        cout << words << endl;
    }
}

既然有人给出了答案,我已经改变了一些程序。那是给你学习的。 这在Visual Studio Express 2012上运行

答案 5 :(得分:0)

我已经使用前面章节中已经学到的想法解决了这个问题,而不是超出你的理解。

#include <iostream>
#include <vector>

using namespace std;

int main()
{ 

vector<string> disliked;

//adding disliked words to the vector

disliked.push_back("dog");
disliked.push_back("cat");
disliked.push_back("goat");
disliked.push_back("cow");
disliked.push_back("sheep");
disliked.push_back("pig");


string words=""; //this variable will store the input from the user.

while(cin>>words)
    {//test every entered word to see if it's equal to any word listed in   disliked words.
        if(words==disliked[0] ||//or
           words==disliked[1] ||//or
           words==disliked[2] ||//or
           words==disliked[3] ||//or
           words==disliked[4] ||//or
           words==disliked[5]){
                               cout<<"Bleeps";}
        else{
             cout<<words;}
}
return 0;
//Not that I have not gone beyond what has been covered in the previous chapters.
//I know their are beautiful solutions to this problem. 
//Keep learning you will know everything.

}

答案 6 :(得分:0)

这个问题是很久以前问过的,因此作者在这一点上可能是专业的,但对于寻求相同答案的任何人来说,这是一个更简单但有效的解决方案。我从头开始学习Bjarne书,因此我暂时还不会“受”高知识的影响而迷惑您,但会根据我们在书中的距离找到足够好的解决方案。 :)

// program that bleeps out words we dont like

vector <string> words;
vector <string> bwords = {"this", "that", "then"}; //bleeped words
string sword; // temporary word

cout << "Enter few words: ";
for (string tword; cin >> tword;)  // read in words
    words.push_back(tword);

//check if they match beeped words

cout << "\n\nWords:\n";
for (int i = 0; i < words.size(); i++)    //take word[i] from the vector
{  
    sword = words[i];    // temporary variable is now word[i]
    for (int j = 0; j < bwords.size(); j++)   // take beeped word[j] from saved words
    {
            if (words[i] == bwords[j]) // is word[i] same as bleeped word[j]
            sword = "BLEEP";  // if word[i] is same then replace sword with BEEP
    }

    cout << sword << "\n"; // now we checked first word and if it matches with any of the bleeped words then it will cout bleep, otherwise it will cout first word.
}

现在在此示例中,您可以添加许多新的bleeped单词,而无需更改代码。 这不是“现实生活”编程中的最佳解决方案,但是在这本书中,我们了解到的是vector(不是很多),cout,cin ..等,所以其他任何事情看起来都令人困惑。关于这一点,我们尚不了解使用::,begin,true / fals,cin.get或类似的内容。

答案 7 :(得分:0)

    $args = array(
            'posts_per_page' => 3,
            'order'          => 'desc',
            'post_type'      => 'post',
            'cat'  => array(19,20,2,3),
            'ignore_sticky_posts' => true
        ); 
   $args['orderby'] = 'post_views';
   $posts = get_posts( $args );

答案 8 :(得分:-1)

“简单可能比复杂更难:您必须努力工作以使您的思路清晰,使其变得简单。但最终还是值得的,因为一旦到达那里,您就可以搬山。” ―史蒂夫·乔布斯

#include "std_lib_facilities.h"

int main()
{
    

    vector<string>disliked;

    disliked.push_back("Apple"); 
    disliked.push_back("OliveOil");
    disliked.push_back("Strawberry");
    disliked.push_back("Lemon");
    
    cout<<"Please type some words:"<<"\n";
    string words=" ";
    while(cin>>words)
    
    {
        if (words==disliked[0] | words==disliked[1]|
            words==disliked[2] | words==disliked[3])
            
        {cout<<"BLEEP"<<"\n";}
    
      else{cout<<words<<"\n";}
    }

    keep_window_open();
}