一个 std::vector 可以 ='d 到另一个 std::vector 吗?
假设我有以下内容:
std::vector<int> myints;
然后我有一个返回 int 向量的函数: 那么
std::vector<int> GiveNumbers()
{
std::vector<int> numbers;
for(int i = 0; i < 50; ++i)
{
numbers.push_back(i);
}
return numbers;
}
我可以这样做吗:
myints = GiveNumbers();
这样做会安全地使 myints 中包含数字 0 到 49 而没有其他内容吗?这样做是否可以清除 myints 中以前可能存在的内容?如果不是,正确的方法是什么?
谢谢
Say I have the following:
std::vector<int> myints;
and then I have a function that returns an int vector:
std::vector<int> GiveNumbers()
{
std::vector<int> numbers;
for(int i = 0; i < 50; ++i)
{
numbers.push_back(i);
}
return numbers;
}
could I then do:
myints = GiveNumbers();
would doing this safely make it so that myints has the numbers 0 to 49 in it and nothing else? Would doing this clear what could have been in myints previously? If not whats the proper way to do this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。这是安全的。您将把
GiveNumbers()
函数的结果复制到myints
中。这可能不是最有效的方法,但它是安全且正确的。对于小向量,效率差异不会那么大。Yes. This is safe. You will be copying the results from your
GiveNumbers()
function intomyints
. It may not be the most efficient way to do it, but it is safe and correct. For small vectors, the efficiency differences will not be that great.是的,它会分配它,并且会清除之前接收向量中的内容。
Yes, it will assign it and it will clear what was in the receiving vector previously.
是的,事实上,
GiveNumbers()
中的返回数字
正在将向量复制到堆栈上。当您使用
operator=
时,您将在新向量上获得相同的内容Yes, as a matter of fact, your
return numbers
inGiveNumbers()
is copying the vector onto the stack.When you use the
operator=
, you'll get the same contents onto your new vector正如已经提到的,这使用起来非常安全,尽管不是最有效的方法。
为了节省资源,最好通过引用传递向量,然后直接修改它。
正如还提到的,对于非常小的向量,效率可能不会产生巨大的差异,但对于较大的向量,效率实际上可能很大。
直接修改原始向量可以通过两种方式实现节省:
As has been mentioned, this is perfectly safe to use, albeit not the most efficient method of doing so.
To save on resources, it may be better to pass your vector in by reference, and modify it directly.
As was also mentioned, the efficiency may not make a huge difference for very small vectors, but on larger vectors can actually be substantial.
The savings you get by modifying the original vector directly are in two ways: