Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 904
Michael Bullock Avatar asked Dec 08 '22 19:12

Michael Bullock


1 Answers

Sure, you can reassign:

*foo = {t};
like image 81
AndyG Avatar answered Dec 20 '22 00:12

AndyG