gpt4 book ai didi

c++ std vector 用现有对象初始化

转载 作者:行者123 更新时间:2023-12-05 09:28:36 27 4
gpt4 key购买 nike

下面是一些代码,其中包含一些已经创建的 Location对象并更新它们。然后它需要构造一个std::vector这些对象传递给其他函数。

我构建 vector 的方式看起来更干净,因为它是一个初始化列表并且是一行,而不是使用 3 push_back初始化空 vector 后调用。因为我们在构建时就知道所有要进入 vector 的元素。

但是,这会导致每个元素生成 2 个拷贝。首先,为什么要在这一行中制作两个拷贝?初始化列表是第一个带有拷贝的构造函数,然后调用 vector 构造函数,因此是第二个拷贝吗? std::vector<Location> pointsVec {l1, l2, l3};

其次,是否有 vector 构造函数或其他技术来仅使用一个拷贝来初始化 vector ? (我想制作 1 个拷贝,因为我仍然想使用本地对象)

struct Location 
{
Location(int x, int y, std::string frame)
: x(x)
, y(y)
, frame(std::move(frame))
{
std::cout << "ctor" << std::endl;
}

Location(const Location & other)
: x(other.x)
, y(other.y)
, frame(other.frame)
{
std::cout << "copy ctor" << std::endl;
}

Location(Location && other)
: x(std::move(other.x))
, y(std::move(other.y))
, frame(std::move(other.frame))
{
std::cout << "move ctor" << std::endl;
}

int x;
int y;
std::string frame;
};

int main ()
{
// local objects
Location l1 {1, 2, "local"};
Location l2 {3, 4, "global"};
Location l3 {5, 6, "local"};

// code that updates l1, l2, l3
// .
// .
// .

// construct vector
std::vector<Location> pointsVec {l1, l2, l3}; // 2 copies per element

std::vector<Location> pointsVec1;
pointsVec1.push_back(l1);
pointsVec1.push_back(l2);
pointsVec1.push_back(l3); // 1 copy per element

return 0;
}

编辑:这个问题一般是针对那些复制起来很昂贵的对象。向该结构添加一个字符串以证明这一点

编辑:添加样本移动构造函数

最佳答案

Is there a vector constructor or another technique to initialize the vector with only 1 copy?

如果将本地对象移动到数组中,则可以从该数组构造 vector ,例如:

// local objects 
Location locs[3]{ {1, 2}, {3, 4}, {5, 6} };

// code that updates locs ...

// construct vector
std::vector<Location> pointsVec {locs, locs+3};

Online Demo

另一种选择是完全摆脱局部对象,首先在 vector 中构造它们,然后只引用这些元素,例如:

// construct vector 
std::vector<Location> pointsVec{ {1, 2}, {3, 4}, {5, 6} };

// local objects
Location &l1 = pointsVec[0];
Location &l2 = pointsVec[1];
Location &l3 = pointsVec[2];

// code that updates l1, l2, l3 ...

关于c++ std vector 用现有对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71211646/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com