Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erasing a pair from vector and reserving space for vector pair

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector < pair <string,int> > ivec;
//ivec.reserve((pair <string,int>)(10);
void logout(int id)
{
    vector < pair<string,int> > :: iterator iter=ivec.begin();
    while(iter!=ivec.end())
    {
        if(iter->second==id){
            ivec.erase(iter);
        }
        ++iter;
    }

}
void login(char str[],int id)
{
    pair<string,int> temp;
    temp.first=(string)str,temp.second=id;
    ivec.push_back(temp);
}
int main(void)
{
    int ch;
    pair<string,int> temp;
    temp.first="server",temp.second=0;
    ivec.push_back(make_pair("server",0));
    while(true)
    {
        char name[10];
        int id;
        cin>>name;
        cin>>id;
        cout<<"login"<<endl;
        cin>>ch;
        if(ch==1)
        {
            login(name,id);
        }
        else
        {
            break;
        }
    }
    cout<<ivec.size();
    logout(6);
    cout<<ivec.size();
}
  1. The logout function to erase the pair from the vector works fine but for erasing the last element it gives a run time error.
  2. I want to reserve space for this vector type but not know the correct syntax to do the job
  3. Please answer according to c++ 98 standard
  4. I am very new to vector and stl so if there is something evern very trivial do mention.
like image 899
Crosk Cool Avatar asked Jan 21 '26 08:01

Crosk Cool


1 Answers

erasing from a vector invalidates the iterator, but erase returns a correct one too.

Do this:

if(iter->second==id){
  iter = ivec.erase(iter);
}
else
  ++iter;

And for the other question.

vector has a reserve function which reserves space. it does not change the size, just the capacity.

vector<pair<string, int> > ivec;

int main()
{
  ivec.reserve(100);
}
like image 117
Serve Laurijssen Avatar answered Jan 22 '26 22:01

Serve Laurijssen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!