How to end a foreach loop in C++?
In C++, the keyword “break” can be used to end a foreach loop. The break statement can be used to prematurely end the loop when a certain condition is met. Here is an example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
for (int num : nums) {
if (num == 3) {
break;
}
std::cout << num << " ";
}
return 0;
}
In the above code, the break statement will immediately end the loop when num equals 3, resulting in the output of 1 2.