Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace all odd values in vector with coresponing value from new vector

Given following vectors:

std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};

In the end I want foo to contain values { 10, 2, 30, 4, 50, 6, 70 } meaning replacing all odd values.

I've tried the algorithm std::replace_if, but how to access the bars corresponding value?

// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  std::replace_if (foo.begin(), foo.end(), IsOdd, 0);

  std::cout << "foo contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}

// output         : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70
like image 971
Lumpi Avatar asked Feb 19 '20 11:02

Lumpi


People also ask

How do you replace an element in a vector?

To replace an element in Java Vector, set() method of java. util. Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.

Can you change values of the vector?

To change the value of a vector item, we refer to their index number or position in the given vector inside brackets [] . We then assign it to a new value.

Can you change values in vector C++?

vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.


2 Answers

You can use the std::transform overload that takes two input iterator ranges:

std::transform(foo.begin(), foo.end(), bar.begin(), foo.begin(),
  [](auto const& a, auto const& b) {
     if (a % 2)
        return b;
     return a; 
  }
);
like image 66
ネロク・ゴ Avatar answered Nov 05 '22 12:11

ネロク・ゴ


Adding to the answers here you can make a function of your own:

Demo: https://godbolt.org/z/yf3jYx

void IsOdd (const std::vector<int>& a, std::vector<int>& b) { 
    for(size_t i = 0; i < a.size() && i < b.size(); i++){
        if(b[i] % 2 == 1)
            b[i] = a[i];
    }
}

and call it in main:

IsOdd(bar, foo);
like image 28
anastaciu Avatar answered Nov 05 '22 12:11

anastaciu