Reputation: 7610
I have 2 vectors of integers. Occasionally, I would like to swap the two (details for why are below). The two options I am considering is using the swap function or swapping the pointers. I see that the swap runs in constant time and seems like the cleaner approach.
More details about the swap: I have multiple threads accessing the first vector. Occasionally I want to do some long running computations on the vector. I still want to collect data from the other threads so I will swap in a different one so the other threads can continue to run during this time
Upvotes: 3
Views: 1491
Reputation: 5005
"I have 2 vectors of integers."
Why? It looks like what you want is a single vector which multiple threads can access (with the appropriate synchronization).
Any "long running function" should just operate on a copy of the first vector.
The code that makes the copy ( just vec2 = vec1;
) should also be synchronized.
The swap
might not be what you want because after swapping, the threads that access the vector will find that the old values in the vector are gone and all they see are the values from the "second" vector. These are not the same unless the second vector is identical with the first, meaning it's a copy, meaning you just swapped a vector with itself...
Upvotes: 0
Reputation: 2745
You should use std::swap witch in algorithm library.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> a;
a.push_back(10);
vector<int> b;
b.push_back(9);
std::swap(a,b);
std::cout<< a[0];
return 0;
}
so you see it swap a and b
Upvotes: 1