Search for nearest element in multidimensional array satisfying some condition

I have a multidimensional array with 20 columns and ‘n’ rows. I’d like to start with the first column, and return the index of the first element in that column satisfying some condition (say, >3). Then, I’d like to move to the second column, and find the index of the ‘nearest element’ satisfying some condition. And similarly for the remaining 20 columns.

To make things more clear, let’s say I have the following array (I’ve made this array far smaller than the actual array for the purposes of demonstration):

``````[1] 1   9   0
[2] 2   2   0
[3] 0   4   1
[4] 5   0   2
[5] 3   0   4
[6] 12  1   6
``````

Let’s say my condition is ‘ > 3 ‘. So, I start with the first column. The first element greater than three is in row [4]. Now, I move to the next column. The first element greater than 3 is in row [1], BUT I want the closest element to row [4] that is greater than 3. That would be the element in row [3]. Similarly for column 3. The one nearest to row [4] is in row [5].

I know there are some very clever things that can be done with the STL algorithms, so perhaps there’s a method there? Or a ‘standard’ algorithm for this task? I’m struggling to think of something that doesn’t involve way too many nested loops or is otherwise really ugly and hard to understand.

Source: Windows Questions C++