how to update value in 2d vector

Problem: i iterated through my 2d int vector and wants to update the element in the vector if it is in a range of values.
This is my code:

1
2
3
4
5
6
7
8
void does_exist(const vector< vector<int> >&  v, int item) {

	vector< vector<int> >::const_iterator row;
	for (row = v.begin(); row != v.end(); row++) {
		if (find(row->begin(), row->end(), item) != row->end())
			v[row][col] = 0;
	}
}


For e.g.,
if i have
10 11 12 13
21 22 23 24


given range 10 to 19:
I want:
0 0 0 0
21 22 23 24


If given range 10 to 19, i want to update value 10,11,12,13 to 0. How can i achieve that?

Last edited on
std::replace_if http://www.cplusplus.com/reference/algorithm/replace_if/

1
2
3
4
5
6
7
8
9
10
11
12
13
void does_exist( const vector<vector<int>>&  table, int key )
{
  for ( auto& row : table ) {
    std::replace( row.begin(), row.end(), key, 0 );
  }
}

void does_exist( const vector<vector<int>>&  table, int low, int high )
{
  for ( auto& row : table ) {
    std::replace_if( row.begin(), row.end(), [low,high](int key){return low <= key && key <= high;}, 0 );
  }
}
Using find, but keskiverto's is way neater :)
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
30
31
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct foo {
    int low, high;
    foo(int l,int h):low(l),high(h){}
    bool between(int v) {
        return v >= low && v <= high;
    }
    bool operator()(int v) {
        return between(v);
    }
};

int main ( ) {
    vector<int> a { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    foo target(4,6);
    for ( auto v = a.begin() ; v != a.end() ; ++v ) {
        auto x = find_if(v,a.end(),target);
        if ( x != a.end() ) {
            *x = 0;
            v = x;
        }
    }
    for ( auto &v : a ) {
        cout << v << endl;
    }
}

Topic archived. No new replies allowed.