我有一个 std::vector<vector<double>>
我想填写一个功能。
我需要存储一些 3 维坐标,以便稍后在我的程序中进行一些计算。
我的问题是如果我这样做:
//in classdefinition
std::vector<std::vector<double>> data;
myFunc()
{
std::vector<double> temp;
temp.push_back(1);
temp.push_back(2);
temp.push_back(3);
data.push_back(temp);
temp.clear();
//new data
temp.push_back(2);
temp.push_back(3);
temp.push_back(4);
data.push_back(temp);
}
temp 的清除和重新填充会影响数据中的值吗?
我已经找到了这个 http://www.cplusplus.com/reference/vector/vector/push_back/ 但由于解释为“val 的内容已复制(或移动)到新元素”。我不知道该怎么想。对我来说,这听起来很矛盾。
我认为如果变量作为引用传递没有多大意义,因为它们就像我的情况一样,只能在有限的范围内有效。 我的假设是否正确?
最佳答案
如果data
类型为 std::vector<std::vector<double>>
那你就没事了:temp
的值拷贝将被采取;所以你可以随心所欲地使用temp
在你将它用作 push_back
之后争论。
但是,如果您弄乱了 vector 的分配器,那么您可能需要更加小心。
使用 emplacement(参见 emplace_back
)可以避免不必要的深层复制:
// First row of data
{
std::vector<double> temp = {1, 2, 3}; /*ain't C++11 brilliant?*/
data.emplace_back(std::move(temp)); /*do not use temp after this line -
use scope blocks so you're not tempted*/
}
您可以单行执行此操作,但实际上我怀疑您想要填充 temp
多一点小心。所以我将这两行分开。
关于c++ - 使用 push_back 将 vector<double> 放入 vector<vector<double>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37939927/