Ioakim Helen
Ioakim Helen

Reputation: 73

C++ : Pop_back a paired vector

I have a paired vector like this

 vector <pair<int , string> > Names;    

I put data in it this way:

cin>>taxi>>Ar_taxis>>Ar_mathiton;

        for(j=0;j<Ar_mathiton;j++)
        {
            cin>>Ar_Mitroou>>Onoma;
            Names.push_back(make_pair(Ar_Mitroou,Onoma));

        }

I sort it and then i print it:

  for(j=0;j<Ar_mathiton;j++)
        {
            cout<<Names[i].first<<" "<<Names[i].second<<endl;
           Names.pop_back();
        }

There's a problem with my pop_back() , it doesn't delete the set of pair. I don't know if there's another command to do it. Thanks.

[edit] the whole code

  cin>>Ar_taxeon;

for(i=0;i<Ar_taxeon;i++)
{
    cin>>taxi>>Ar_taxis>>Ar_mathiton;

        for(j=0;j<Ar_mathiton;j++)
        {
            cin>>Ar_Mitroou>>Onoma;
            Names.push_back(make_pair(Ar_Mitroou,Onoma));

        }

        sort(Names.begin(),Names.end());

        cout<<taxi<<Ar_taxis<<endl;
        for(j=0;j<Ar_mathiton;j++)
        {
            cout<<Names[i].first<<" "<<Names[i].second<<endl;
           Names.pop_back();
        }

}

Upvotes: 0

Views: 1642

Answers (2)

user2209008
user2209008

Reputation:

There's a variety of problems with the example you posted.

The first one is that you are iterating over the list using j, but accessing Names with the index of i. However, even if you fixed that you would get a crash because you are iterating forward through the vector, but popping off the back, this means that you will eventually get an out-of-range error as the iterating index passes over the length of the list.

If you want to remove all items in one go, you should just call Names.clear().

Additionally, it's bad form to be using C++ and not using the C++ way of iterating through lists.

Consider changing your second loop to the following:

for (auto& name : Names)
{
    cout << Names[j].first << " " << Names[j].second << endl;
}

Then finally, call this:

Names.clear();

Upvotes: 0

user5473178
user5473178

Reputation:

Consider following changes:

change name of variable i inside loop into j

and you can call Names.clear() after cout, instead of Names.popBack():

so your final code will be:

#include <iostream>
#include <vector>
using namespace std;
int main(){
vector <pair<int , string> > Names;

int Ar_mathiton,Ar_Mitroou;
string Onoma;
cin>>Ar_mathiton;

for(int j=0;j<Ar_mathiton;j++)
{
    cin>>Ar_Mitroou>>Onoma;
    Names.push_back(make_pair(Ar_Mitroou,Onoma));

}
for(int j=0;j<Ar_mathiton;j++)
{
    cout<<Names[j].first<<" "<<Names[j].second<<endl;

}
Names.clear();

return 0;
}

Upvotes: 1

Related Questions