0

I recently learned how to use the vecor library in C++. I don't understant what is the vector default constructor or when should I use it.

If for example I have a struct and want to create a vector of n structs. Is the following code valid:

 struct item
{
    string id;
    string name;
};

    vector <item> vitem;

    vitem.push_back(item()); 

Does this vector have one element? or no elements at all?

2
  • 1
    std::cout << vitem.size() << std::endl holds the answer to your question. Commented Nov 3, 2013 at 10:49
  • After the default constructor the vector contains zero elements, and after pushing one element into the vector you have one element. Commented Nov 3, 2013 at 11:06

3 Answers 3

1

Yes, this calls the default constructor. A default constructor is a constructor that takes no arguments. The default constructor of std::vector initializes the vector with zero elements.

std::vector<item> items; // implicitly calls default constructor
Sign up to request clarification or add additional context in comments.

4 Comments

Okay. Is it always necessary to call it? like when constructing a class?
You don’t have to call it explicitly. The compiler inserts the call for you.
One last question. If I want to add more elements to the vector using the push_back function should I use the constructor again?
@Reboot_87 No. Once the vector is constructed you can add elements without constructing it again.
0

It has. The ctor is called immediately if you are declaring vector as var instead pointer.

Comments

0

If for example I have a struct and want to create a vector of n structs. Is the following code valid:

No, this code is invalid because it does not create a vector of n structures. It creates an empty vector. If you want to create a vector of n structures you should explicitly specify the number of created elements. For example

std::vector<item> vitem( n );

or you can at first create an empty vector and then resize it. For example

srd::vector<item> vitem;
vitem.resize( n );

Or you can use method assign

std::vector<item> vitem;
vitem.assign( n, item() );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.