+ 1

# Comparing two vectors but getting random number

I have a problem where when I compare a number with another empty number I get a random number. https://code.sololearn.com/cGoECLzUyQMr/?ref=app

8 Answers

+ 1

The problem with the current code is that when checking for the smallest vector, you're not using the variable, nor do you know which vector is the big or small one.
Pointers would be perfect here, as in:
std::vector<int>* small, *big;
if(vec_a.size() < vec_b.size()){
small = &vec_a;
big = &vec_b;
}else{
small = &vec_b;
big = &vec_a;
}
From here on whenever you use small or big you're automatically using the correct one.
Then depending on your previous answer of "what should max do?"
Remember that the vector default initializes the values after you resize it, for an int that's 0.
max( -1, 0 ) where the 0 didn't exist before = -1 or 0?
If it should be -1 then do:
transform with the pointers, small in the 1st 2, big in the 3rd,
resize result to the big size,
copy from big->begin() + small->size() to result.
If it should be 0:
resize small to big->size(),
don't bother copying,
transform big in the first 2, small in the 3rd

0

Well, the vectors are of different sizes. It seems to be adding default initialized integers (zero) for comparison. So, 0 is larger than -3 and 7 is larger than 0. Thus the 0 and 7 at the end.

0

The numbers are random. I need to find a way of doing it without hardcoding it.

0

Yones Mussa I am getting 10, 20, 0, 7. Consistently. Is it random for you? Is all of them random or just the last two?

0

Mustafa A The size of the vectors are random.

0

std::transform requires that the 2nd vector has at least the size of the first vector.
If your vectors are of different sizes then std::transform might not be a good idea to use.
What should the result of max of number a and the 'non existing' number b mean anyway?
If the answer is 'a' then iterate over the smallest vector and copy the rest from the big vector.

0

Can you see what im doing here?
https://code.sololearn.com/cTJH19vg2UpA/?ref=app