how to seach on a vector and replace the found element with another vector element

Hi all,
I am leaning STL algorithm, especially on iterator.

I have two vector, src and data. I am going to search all elements with value more than 100 and replace the found elements with the one stored in data. I try the following code, it found the element but the replacement seems not working (it replace the element with some random number). Also I wonder if there is more compact way (like using STL algorithm) to do the same thing? I found replace_if but sees that if can only replace the elements with a constant value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void main(void)
{
  std::vector<int> src, data;

  for (int i=0; i<100; i++) data.push_back(i+200);
  src.push_back(1);
  src.push_back(2);
  src.push_back(102);
  src.push_back(3);
  src.push_back(109);
  src.push_back(3);
  src.push_back(102);
  src.push_back(55);
  src.push_back(5);

  auto it=std::begin(src), itd=std::begin(data);
  do
  {
    it = std::find_if (std::begin(src), std::end(src), [](int x){return x>100;});
    if (it!=std::end(src))
    {
      *it = *itd;
      itd++;
    }
  } while (it!=std::end(src));
  std::ostream_iterator<int> out_it (std::cout,", ");
  std::copy ( src.begin(), src.end(), out_it );
}

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>

int main()
{
    std::vector<int> srce { 1, 2, 102, 3, 109, 3, 102, 55, 5 } ;

    std::vector<int> data( srce.size() ) ;
    // http://en.cppreference.com/w/cpp/algorithm/iota
    std::iota( std::begin(data), std::end(data), 200 ) ;

    // http://en.cppreference.com/w/cpp/algorithm/transform
    std::transform( std::begin(srce), std::end(srce), std::begin(data), std::begin(srce),
                    []( int sval, int dval ) { return sval > 100 ? dval : sval ; } ) ;

    for( int value : srce ) std::cout << value << ' ' ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/3d3e4bb7e558f45a
Thanks a lot.
Topic archived. No new replies allowed.