将向量分配给单个元素

Assigning a vector to a single element

考虑 std::vector<T> 某种类型 T。我收到一个指向这种类型的函数的指针,还有一个 T 的实例; t 说。

我的函数如下所示:

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

有没有办法在一条语句中编写函数体? *foo = t; 由于不存在适当的赋值运算符而不起作用。我也在考虑使用

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

但这看起来很调皮。

我正在使用 C++11。

当然,您可以重新分配:

*foo = {t};

有什么理由不能只使用 std::vector<>other assign() 成员函数吗?

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