There is a student class
class Student
{
public:
inline static int current_id_max = 0;
int id = 0;
string name;
public:
Student()
{
id = (++current_id_max);
cout << "Student constructor\n";
}
Student(const string& _name)
{
name = _name;
id = (++current_id_max);
cout << "Student constructor: " << _name << endl;
}
Student(const Student& o)
{
name = o.name;
id = (++current_id_max);
cout << "Student constructor copy: " << name << endl;
}
~Student() { cout << "Student destructor: " << name << endl; }
};
I want to create 5 students with parameters into a vector,
std::vector<Student> school =
{ Student("Tom"), Student("Mike"),Student("Zhang"), Student("Wang"), Student("Li")};
There will be 5 Student constructor: name
and 5 Student constructor copy: name
.
What can I do to avoid the useless copying?
Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*> instead of std::vector<whatever> .
At the time of declaration of vector, passing an old initialized vector copies the elements of the passed vector into the newly declared vector. They are deeply copied.
Algorithm. Begin Initialize a vector v1 with its elements. Declare another vector v2. Make a for loop to copy elements of first vector into second vector by Iterative method using push_back().
5) std::copy() function And yes, it does a deep copy.
I suggest the following:
std::vector::emplace_back
to add elements to it.A complete example:
#include <iostream>
#include <vector>
#include <string>
class Student
{
public:
inline static int current_id_max = 0;
int id = 0;
std::string name;
public:
Student()
{
id = (++current_id_max);
std::cout << "Student constructor\n";
}
Student(const std::string& _name)
{
name = _name;
id = (++current_id_max);
std::cout << "Student constructor: " << _name << std::endl;
}
Student(const Student& o)
{
name = o.name;
id = (++current_id_max);
std::cout << "Student constructor copy: " << name << std::endl;
}
~Student() { std::cout << "Student destructor: " << name << std::endl; }
};
int main()
{
std::vector<Student> school;
school.reserve(5);
school.emplace_back("Tom");
school.emplace_back("Mike");
school.emplace_back("Zhang");
school.emplace_back("Wang");
school.emplace_back("Li");
}
Output in my test:
Student constructor: Tom
Student constructor: Mike
Student constructor: Zhang
Student constructor: Wang
Student constructor: Li
Student destructor: Tom
Student destructor: Mike
Student destructor: Zhang
Student destructor: Wang
Student destructor: Li
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With