How to define vectors end so it won't go on en

2019-07-19 06:19发布

问题:

At the moment I have a text file containing information pertaining to different musicals artists.

David Byrne 1 Talking_Heads Lead-Vocals
Chris Frantz 1 Talking_Heads Drummer
Tina Weymouth 3 Talking_Heads Compass_Point_All_Stars Tom_Tom_Club Bass

In this order it goes Forname,Surname,The number of bands they were in,The bands they where in and finally there role within the band. When searching for people the bands are put into a vector to be displayed but this vector is not ending so when searching for Tina Weymouth for example it will show the previous two entries bands as well as Tina's.

while (artist >> forname >> surname >> bandnum)
    {
        for (int i = 0; i < bandnum; i++)
        {
            string tmp;
            artist >> tmp;
            band.push_back(tmp);
        }
        artist >> role;


        if (strF == forname && strS == surname) {
            system("CLS");
            cout << "Artist found" << endl;
            cout << forname << " " << surname << " ";
            ostream_iterator<string> output_iterator(cout, " ");
            copy(band.begin(), band.end(), output_iterator);
            cout<< role << endl;
            system("pause");
        }
    }

Above is the code used it should read the number before there names and make a vector that size which contains each band instead it is making an endless vector.

回答1:

You overwrite the values of forname, surname, bandnum and role every loop, but you leave the band vector to keep growing and growing--keeping information about past artists. You need to clean and clear it after every loop!

A simple call to clear() is all you need. Just add the following line at the start (or end if you prefer) of your while loop:

band.clear();

Here it is in action: ideone



标签: c++ vector