Home > Net >  Why vector push_back call twice in C ?
Why vector push_back call twice in C ?

Time:09-17

In the following program, I have created 3 object of class Person and pushed that object into vector container. After that, the display function is called using a range based for loop and printing the name and age.

#include <iostream>
#include <vector>
#include <iterator>
#include <functional>
 
using namespace std; 

class Person
{
    private:
        string _name;
        int _age;
        
    public:
    
    Person()
    {
    
    }

    Person(string name, int age) : _name(name), _age(age)
    {
        
    }

    void Display()
    {
        cout<<"_name : "<<_name<<" => "<<"_age : "<<_age<<endl;
    }
};

int main()
{
    Person p1("User1", 20);
    Person p2("User2", 30);
    Person p3("User3", 25);
    
    vector<Person> per(3);
    
    per.push_back(p1);
    per.push_back(p2);
    per.push_back(p3);
    
    for(auto obj : per)
    {
        obj.Display();
    }
}

But I don't understad what am I missing here to get output

_name :  => _age : -1
_name :  => _age : -1
_name :  => _age : -1
_name : User1 => _age : 20
_name : User2 => _age : 30
_name : User3 => _age : 25

instead of

_name : User1 => _age : 20
_name : User2 => _age : 30
_name : User3 => _age : 25

Thanks in advance.

CodePudding user response:

When you define the vector:

vector<Person> per(3);

you set the size to 3, which means three default-constructed elements will be created and added to the vector.

You then add three more, so you have a total of six elements in the vector.

If you only want your three elements there are a few alternatives:

  1. Reserve the memory only, do not set the size:

    vector<Person> per;
    per.reserve(3);  // Allocates memory for 3 elements, doesn't set the size
    per.push_back(p1);
    per.push_back(p2);
    per.push_back(p3);
    
  2. Don't push back, use indexing to set the elements:

    vector<Person> per(3);
    per[0] = p1;
    per[1] = p2;
    per[2] = p3;
    
  3. Initialize the vector with the elements you want:

    vector<Person> per = {
        { "User1", 20 },
        { "User2", 30 },
        { "User3", 25 }
    };
    

CodePudding user response:

You are creating a vector of size 3, and after that, you are adding 3 more elements to that vector. Try printing out the number of elements stored in your vector (per.size()) after inserting your 3 persons.

  • Related