【问题标题】:Copying one vector to Another in least time complexity?以最少的时间复杂度将一个向量复制到另一个向量?
【发布时间】:2021-01-23 01:16:01
【问题描述】:

我有两个向量 old 和 newone
我想将 newone 的值复制到 old 中最快的方法是什么
我认为我可以使用指针,但我也认为分配
newone = old
也会这样做

#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;
    }
}

有没有什么方法可以在 0(1)/常数时间内完成??除了指针

【问题讨论】:

  • 您不能在O(n) 时间内复制大小为n 的向量。不过,您可以在恒定时间内移动它。
  • newone = std::move(old);

标签: c++ stl stdvector


【解决方案1】:

就像评论中所说的,您可以使用移动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::moveold 标记为临时,然后vector 的复制运算符将选择带临时的重载并“窃取”old 的数据。

过去//1old处于状态调用“moved from”,基本上该对象处于有效状态,但你不能假设任何关于这个状态,你必须检查它(通过例如.size())

如果您想了解更多关于移动的信息:check out this


注意:Why should I not #include &lt;bits/stdc++.h&gt;?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    相关资源
    最近更新 更多