You can't use break
in a conditional. To hack this up using a non-throwing conditional (for educational purposes per your comments), you actually need it in the for
loop as follows:
for (int i = 0; i < x.size(); i = x[i] == rating
? ((cout << "found at " << i), x.size())
: i + 1)
;
What this does is advance i
to x.size()
(so the loop will terminate) when the rating is found (after evaluating output and ignoring it using the comma operator), otherwise moving i
to the next element index (i + 1
). Put another way, the use of the conditional operator above is equivalent to:
if (x[i] == rating)
{
std::cout << "found at " << i;
i = x.size(); // poor man's "break"
}
else
i = i + 1;
(You could of course put the code immediately above in the statement controlled by your for
loop... for (size_t i = 0; i < x.size(); ) if (x[i] == ...
), but then you wouldn't be using the conditional operator (and could use an actual break, and might as well use ++i
in the for
advancement statement and ditch the else
above, at which point you have R Sahu's answer).
I put a complete demo program on coliru.stacked-crooked.com.
As I mentioned in a comment, you can't break
in a conditional, but you can throw
. Using exceptions for an event you expect to occur is generally frowned upon (a coding convention that reserves them for unexpected events helps other programmers understand how you're expecting your program to run), but it's possible:
int main()
try
{
...
for (size_t i = 0; i < x.size(); ++i)
x[i] == rating ? throw i : (void)0;
}
catch (size_t i)
{
std::cout << "found at " << i << '\n';
}
You can find/run/edit this on coliru here. Note (void)0
is evaluated but does nothing - it has no side effects. You could use any expression there - 0
, 'x'
, nullptr
- but prefixing with (void)
emphasises that the value can't and won't be read and used for anything. So it would be equivalent, clearer and more concise to use if (x[i] == rating) throw i;
if we weren't set on using the conditional operator.
How you should actually write it if you're not trying to teach yourself how to abuse conditional operators:
std::cout << "found at " << x.find(rating) - x.begin() << '\n';
Often when you use find
you should be checking against x.end()
to see if your value was found, but in your case you know 100% that the value is in the vector so can safely keep the code simple.