Suppose Foo
is any class.
Foo f[5];
std::vector<Foo*> v;
I can insert the elements into vector of pointers using a for loop statement:
for (size_t i = 0; i < 5; i++)
v.push_back(&f[i]);
Is it possible to insert them using std::vector::insert()
function and why not? I have tried several times it failed something like this:
v.insert(v.end(), &f[0], &f[5]); // error
If you mean, with a single call to insert
, then no - that can copy a range, performing type conversions if needed, but can't apply arbitrary transformations like taking the address of each element.
You could use std::transform
:
std::transform(std::begin(f), std::end(f),
std::back_inserter(v),
[](Foo & f) {return &f;});
although that's probably less clear than a simple loop, especially if you use new-style syntax
for (Foo & foo : f) {
v.push_back(&foo);
}
Yes you can use insert also. But there are few differences between these two operations:-
push_back puts a new element at the end of the vector and insert allows you to select position. This impacts the performance. insert forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert might often be less efficient than push_back.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.