Использование векторов для вывода некоторых предопределенных строк - PullRequest
3 голосов
/ 28 апреля 2011

Итак, я сейчас выполняю упражнения в своей книге по программированию «Программирование: принципы и практика с использованием 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

Ответы [ 8 ]

4 голосов
/ 28 апреля 2011

Хорошо, позвольте мне объяснить простой подход к этому. Есть и более элегантные, но сейчас важно, чтобы вы почувствовали, как получить доступ к 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 в последнем примере кода, если немного реструктурировать. Я оставлю это вам в качестве упражнения (подсказка: оставьте итератор живым и проверьте его значение после завершения цикла).

0 голосов
/ 11 июля 2019
//Josef.L
//2019/7/11

int main(void){
    vector <string> inpute;
    for(string pat; cin >>pat;){
        inpute.push_back(pat);
    }
    for(int i=0; i < inpute.size(); i++){
        if("work"== inpute[i]){
            cout<<"bleep! "<<endl;}
        else if("life" == inpute[i]){
            cout<<"bleep! "<<endl;
        }
        else if("broccoli" == inpute[i]){
            cout<<"bleep! "<<endl;
        }
        else if("homework" == inpute[i]){
            cout<<"bleep! "<<endl;
        }
        else{
            cout <<inpute[i]<<endl;
        }

    }
return 0;}
//However, the entire source code is too long and boring, so there should be an improvement.

0 голосов
/ 22 июня 2019

Этот вопрос задавался давным-давно, поэтому автор, вероятно, профессионал в этом вопросе, лол, но здесь есть более простое, но работающее решение для любого, кто ищет тот же ответ. Я учусь с самого начала через книгу Бьярне, так что я еще не «затронут» более высоким знанием, чтобы запутать вас, но решениями, которые достаточно хороши, чтобы работать, основываясь на том, как далеко мы в книге. :)

// 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.
}

Теперь в этом примере вы можете добавить много новых выделенных слов, и вам не нужно менять код. Это не лучшее решение в программировании "в реальной жизни", но на данный момент в книге мы изучили, если, vector (не много), cout, cin ... и т. Д., Так что все остальное просто выглядит запутанным ... до этот момент мы еще не знаем об использовании ::, begin, true / fals, cin.get или чего-либо подобного.

0 голосов
/ 19 июля 2016

Я решил эту проблему, используя идеи, которые уже были изучены в предыдущих главах, не выходя за рамки того, что вы понимаете.

#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.

}

0 голосов
/ 11 апреля 2015

Я изучаю C ++. Эта программа была несколько изменена. Напишите программу, которая "выдает" плохие слова, которые вам не нравятся; то есть, вы читаете словами cin и снова печатаете их на cout. Если слово входит в число определенных вами, вы выписываете BLEEP и вместо этого слова получаете BLEEP (Звук). Начните с одного "плохого слова", такого как - string badword = "ass"; Когда это сработает, добавьте еще несколько или напишите целую программу, основанную на всех плохих словах, которые вы не хотите печатать.

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

0 голосов
/ 15 июня 2014

Вот мое решение этого конкретного вопроса в книге, когда я его читал.:) надеюсь, это говорит само за себя.

/*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!".
       }
   }


}
0 голосов
/ 28 апреля 2011

используйте std :: find (your_vector.begin (), your_vector.end (), слова)

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;
}
0 голосов
/ 28 апреля 2011
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> к вашему источнику.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...