简体   繁体   中英

c++ vector push_back problems

I have a problem with my exercise code. If I enter the name and score value the values aren't getting pushed into the vector. Here is my code:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    while(true)
    {
        vector<string> names = {"test"};
        vector<int> scores = {0};

        string name = "none";
        int score = 0;

        cin >> name >> score;
        if(name == "print" && score == 0)
        {
            for(int i = 0;i<names.size();++i)
            {
                cout << "name:" << names[i] << " score:" << scores[i] << "\n";
            }
        }
        if(name == "NoName" && score == 0)
        {
            break;
        }
        if (find(names.begin(), names.end(), name) != names.end())
        {
            cout << name << " found name in names, you can't use this name.\n";
        }else{
            names.push_back(name);
            scores.push_back(score);
        }
    }
} 

the else-statement where the values are getting pushed in the vector is getting called but it doesn't push the values in the vector.

Your issue here is names and scores are declared inside the while loop. That means every iteration they are constructed, used, and then destroyed. This means in every iteration you have fresh vectors. You need to move the vectors out of the loop so they persist through the entire execution of the loop.

vector<string> names = {"test"};
vector<int> scores = {0};
while(true)
{
    string name = "none";
    int score = 0;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM