Here are two different type of std::vector, as an example:
std::vector<std::reference_wrapper<MyClass>> rv;
std::vector<MyClass> v;
A possible way to assign between them is:
for (const auto& mc : rv) {
v.push_back(mc.get());
}
It works. But ugly and maybe slow. The same as comparison:
bool is_same(std::vector<MyClass>& v, std::vector<std::reference_wrapper<MyClass>>& rv) {
if (v.size()!=rv.size()) {
return false;
}
for (size_t i = 0; i < v.size(); v++) {
if (v[i]!=rv[i].get()) {
return false;
}
}
return true;
}
Is there any better way to do this work? Smart and quick.
Since
std::reference_wrapper
is implicitly convertible to a reference to the type it holds, you can assign one toMyClass
. So a better way to initialize one with the other is the appropriate vector constructor:Or, if you really need to assign:
You can do the comparison by applying the
std::mismatch
algorithm, again thanks to the implicit conversion provided bystd::reference_wrapper
:As a general rule of thumb, it's always good to consult the standard algorithm library before writing loops yourself. It makes your own code more readable by giving verbs and nouns to computation steps. And has the benefit of allowing for any optimizations the standard library can offer.
As cppleaner pointed out, I should have consulted the library more closely myself.
is_same
can be implemented even more easily by a simple call tostd::equal