Confused

closed account (yboiAqkS)
Can someone help me understand this answer? Im taking an online course that has quizzes that doesn't require using cin or cout. But am having difficult time understanding using while loops with vectors.
int count{0};

size_t index{0};

while(index < vec.size() && vec.at(index) != -99){

++count;

++index;

}

Last edited on
It's iterating through each element of the vector, and exiting the loop early if the current element, vec.at(index), is -99.
when using C style arrays, it is common to have a 'sentinel' value that means "this and beyond are not holding real data".
eg int x[100];
x[0] = 1;
x[2] = -99; //while x holds 100 items, currently, it has 1 item, the -99 (this can be any value that isnt valid in your data, so say x is meant to hold small positive values) tells you to stop there.

we don't need this anymore. vectors have better tools; this is crude.

that makes this example... very odd, to say the least.

also, use .at only if the index can go out of bounds due to some weird reason, like a computed index from a hash function, maybe. If you know the range, use [] as it is much faster than at() and does the same thing (but skips the sluggish 'is it in range checking'). Here you KNOW that index is safe, its < size(), so it can't go out on the positive side, and you started at zero. so [index] is better.
Last edited on
closed account (yboiAqkS)
Thank you!! Makes a lot of sense now.
Topic archived. No new replies allowed.