Minimize the push_back code

I need to minimize my code
Task: Write a string variables to input stream with filter, and get vector's data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>

int main()
{
    using namespace std;

    vector<string> names;

    for (string a; cin >> a;)
    {
        if (a == "bad")
        {
            a = "BLEEP";
        }

        names.push_back(a);
        cout << "Number of names: " << names.size() << '\n';
    }
    for (string b : names)
    {
        cout << b << '\n';
    }
}
Last edited on
Why do you need to minimize your code ?
It looks fine and seems to work.
Hello sadibekov,


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button, but you may still to indent your code.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



The first thing I see is the for loop is an endless loop with no way out. You might want to add code to check a key word to break out of the loop.

The "cout" statement might work better outside the for loop instead of printing it with each loop iteration.

You wrote:
Task: Write a string variables to input stream with filter, and get vector's data.

I do not quite understand what is meant by "filter".

After running the program you need a prompt before the "cin" to tell the user what to enter.

No one likes looking at a blank screen and wondering what to do.

Andy
@Handy Andy,
for (string a; cin >> a;)
I think you are supposed to stop the input with Ctrl + Z.
This loop code looks like one I saw in a book from B. Stroustrup.

The "cout" statement might work better outside the for loop instead of printing it with each loop iteration.
Outside the loop you can't access the string b.

I do not quite understand what is meant by "filter".
I think the filter is the replace of "bad" with "BLEEP"
if you use reserve() push_back will not need to allocate memory as often. This helps performance if you have a rough idea of the amount of data your program will handle 'typically'. http://cplusplus.com/reference/vector/vector/reserve/
has an example of this in action.
Last edited on
Thanks
Topic archived. No new replies allowed.