Michael Bullock Michael Bullock -4 years ago 151
C++ Question

Assigning a vector to a single element

Consider

std::vector<T>
for some type
T
. I receive a pointer to such a type into a function, and also an instance of
T
;
t
say.

My function looks like this:

void bar(std::vector<T>* foo, const T& t)
{
foo->clear();
foo->push_back(t);
}


Is there a way I write the function body in one statement?
*foo = t;
does not work due to an appropriate assignment operator not existing. I was also thinking of using

foo->assign(&t, &t + 1);


but that seems naughty.

I'm using C++11.

Answer Source

Sure, you can reassign:

*foo = {t};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download