Finding the smallest value in two arrays related Hello everyone,
I have a small question. I have two vectors as follows:
A=[3 0 0 7]
B=[5 3 8 9]

I need to find the index of the smallest values of A which are 0,1 which correspond to the value 0.
Then, I need to choose the index amoung these indexes which corresponds to the smallest value in B ie, I need to choose index 0 between 0 and 1, which corresponds to smallest value ,3, in vector B. The problem I face, I do not want to use push_back to save the indexes of A since it is costly. How can I achieve this task in an easiest and least costly way ?
Thank you so much A=[3 2 7 2]

The smallest value in A is apparently 2. The value 2 appears at indices 1 and 3.
 B=[5 4 8 9]

Indices 1 and 3 in B contain values 4 and 9. The smallest of them is 4.

The push_back(), specifically vector::push_back() may be costly if vector has to reallocate. It is possible to preallocate, which ensures that push_back will not reallocate. Hence that cost is not so real.

However,
 auto aMin = *std::min_element( begin(A), end(A) ); FOR each index i IF Ai == aMin THEN consider Bi for bMin Let's clarify some things: You're asking for the most efficient way to find the smallest corresponding value between two vectors. Is it the value that you need or do you specifically need the index of that smallest value?

I'm assuming both the vectors may be any length in this problem.

How do you feel about sorting the vectors? Or does the index of the values have to remain unchanged?

Edit: nevermind, thanks kbw.
Last edited on If you sort the vectors, you'll change the index of the item that has zero. You have to search the existing container as it is. 12345678910111213141516171819202122232425262728 #include #include using namespace std; int minmin( const vector &A, const vector &B ) { int minA = A, minB = B; for ( int i = 1; i < A.size(); i++ ) { if ( A[i] == minA ) { if ( B[i] < minB ) minB = B[i]; } else if ( A[i] < minA ) { minA = A[i]; minB = B[i]; } } return minB; } int main() { vector A = { 3, 0, 0, 7 }; vector B = { 5, 3, 8, 9 }; cout << minmin( A, B ) << '\n'; }

 A=[3 0 0 7] B=[5 3 8 9] I need to find the index of the smallest values of A which are 0,1

Nonsense: those indices would be 1 and 2.  