Question

I have an interesting problem. I am simplifying it here.

I have one vector that contains: a = { 13, 56, 76, 24} Another vector contains: b = { 2, 74, 16, 29}

I want to exchange the values, let's say 56 and 2. So I want my arrays to be:

a = {13, 2, 76, 24} b = {56, 74, 16, 29}

So the problem is: I add values to my vectors with push_back and I do not know where these values are stored in each vector. So I know that there is 2 somewhere in vector b and there is 56 somewhere in vector a. How can I perform this change?

Was it helpful?

Solution

  1. Use std::find to find the elements in each vector
  2. Check that the elements have been found
  3. Swap the elements using std::iter_swap.

Example:

auto ita = std::find(a.begin(), a.end(), 56);
auto itb = std::find(b.begin(), b.end(), 2);
if (ita != a.end() && itb != b.end())
  std::iter_swap(ita, itb);

OTHER TIPS

std::vector<int>::iterator it56 = std::find( vec56.begin(), vec56.end(), 56);
std::vector<int>::iterator it2 = std::find( vec2.begin(), vec2.end(), 2);
if ( it56 != vec56.end() && it2 != vec2.end()) {
  *it56 = 2;
  *it2 = 56
  // or: std::iter_swap(it56, it2);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top