-1

I have two vectors old and newone
I want to copy the value of newone into old what would be the fastest method to do so
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 ?? besides pointers

cigien
  • 57,834
  • 11
  • 73
  • 112
ASHUTOSH SINGH
  • 131
  • 1
  • 13

1 Answers1

0

Like it was said in comment, you can use 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.

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())

If you want more info about move : check out this


Note: Why should I not #include <bits/stdc++.h>?

Martin Morterol
  • 2,560
  • 1
  • 10
  • 15