Considering this example:
std::vector<Student> students;
//poplate students from a data source
std::vector<Student> searched(students.size());
auto s = std::copy_if(students.begin(), students.end(), searched.begin(),
[](const Student &stud) {
return stud.getFirstName().find("an") != std::string::npos;
});
searched.resize(std::distance(searched.begin(), s));
I have the following questions:
- Is it ok to allocate memory for searched vector equals to the initial vector? There may be 500 not small objects and maybe none satisfying the search criteria? Is there any other way?
- When copying to the searched vector it is called the copy assignment operator and ..obviously a copy is made. What if from those 500 objects 400 satisfying the search criteria? Isn't just memory wasting?
I am a c++ noob so I may say something stupid. I don't see why to ever use vector<T>
where T
is a object. I would always use vector<shared_ptr<T>>
. If T
is a primitive type like an int i guess it's kinda straight forward to use vector<T>
.
I considered this example because I think it's very general, you always have to pull some data out of a database or xml file or any other source. Would you ever have vector<T>
in your data access layer or vector<shared_ptr<T>>
?