Assigning a vector to one element

Consider std::vector<T>for some type T. I get a pointer to this type in the function, as well as an instance T; Tlet's 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 to write a function body in a single expression? *foo = t;does not work due to the lack of an appropriate assignment operator. I also thought about using

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

but it seems naughty.

I am using C ++ 11.

+4
source share
2 answers

Of course you can reassign:

*foo = {t};
+10
source

Is there a reason you can't just use the std::vector<> other function assign()?

void bar(std::vector<T>* foo, const T& t)
{
    foo->assign(1, t);
}
+4

Source: https://habr.com/ru/post/1671063/


All Articles