[英]Copying one vector to Another in least time complexity?
I have two vectors old and newone我有两个向量 old 和 newone
I want to copy the value of newone into old what would be the fastest method to do so我想将 newone 的值复制到 old 中,这是最快的方法
I think i can use pointers but i also think assigment我想我可以使用指针,但我也认为赋值
newone = old新的=旧的
will do the same会做同样的事情
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main()
{
vector<int> old = {1,2,3};
vector<int> newone = {4,5,6};
newone = old;
for( auto x : newone ){
cout<<x<<endl;
}
}
Are there any methods to do itin 0(1)/constant time ??是否有任何方法可以在 0(1)/恒定时间内完成? besides pointers
除了指针
Like it was said in comment, you can use move the vector
.就像评论中所说的那样,您可以使用 move the
vector
。
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> old = {1,2,3};
vector<int> newone = {4,5,6};
newone = std::move(old); // 1
for( auto x : newone ){
cout<<x<<endl;
}
}
std::move
while flag old
as a temporary, then the copy operator of vector
will select the overload which takes a temporary and ''steal'' the data of old
. std::move
old
标记为临时的,然后vector
的复制运算符将选择采用临时的重载并“窃取” old
的数据。
Past the //1
, old
is in a state call " moved from ", basically the object is in a valid state, but you can't suppose anything about this state, you have to check it (by example with .size()
)过去
//1
, old
处于状态调用“ moved from ”,基本上对象处于有效状态,但是您不能假设有关此状态的任何信息,您必须检查它(例如使用.size()
)
If you want more info about move : check out this如果你想了解更多关于移动的信息: 看看这个
Note: Why should I not #include <bits/stdc++.h>
?注意: 为什么我不应该
#include <bits/stdc++.h>
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.