3
#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.
Crosk Cool
  • 664
  • 2
  • 12
  • 27

1 Answers1

4

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);
}
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
  • Thank you , and how to reserve let say 10 elements of this vector type? – Crosk Cool Apr 20 '16 at 07:34
  • To add to what @HumamHelfawi said: That's not the capacity. It is the number of elements that the vector is initialized with (in your example, you get 100 default-constructed `pair`s in your vector - the *actual* capacity may very well be different) – hlt Apr 20 '16 at 07:42
  • The constructor method you just mentioned about did not increased the capacity of the vector to 100 as reserve would do. So how to use reserve? – Crosk Cool Apr 20 '16 at 07:45
  • It gives a compiler error "v does not name a type" @ServéLaurijssen – Crosk Cool Apr 20 '16 at 07:53
  • http://ideone.com/V86SB8 There is a compiler error using the reserve by this naive way v.reserve(100) as vector is of type(pair) @ServéLaurijssen – Crosk Cool Apr 20 '16 at 08:11
  • it compiles fine here. whats the error? there's probably something else wrong – Serve Laurijssen Apr 20 '16 at 08:21