Let the standard library find a bad index for you, and recover when it does.
What to build
A program that looks up positions in a vector and reports bad ones with an exception.
Requirements
- Use
at(), not[], for every lookup. - Catch
out_of_rangeby const reference. - Print
bad index Ifor an index that is not valid, and carry on with the next one.
Input
The first line has n, and the second line the n numbers. The third line has q, and the fourth line the q indexes.
Output
One line per index: the number at that index, or bad index I.
Constraints
1 ≤ n, q ≤ 100, and each index is from -1000 to 1000.
Example
Input:
3
10 20 30
4
0 2 3 -1
Output:
10
30
bad index 3
bad index -1
Why it works
at() throws instead of reading memory it does not own, and the catch turns that into a message. Because each lookup has its own try block, the program goes on to the next index.
Examples
3 10 20 30 4 0 2 3 -1
10 30 bad index 3 bad index -1
1 5 1 0
5
Hints
Hint 1
`v.at(i)` checks the index and throws `out_of_range` when it is not valid. `v[i]` does no check.
Hint 2
Put each lookup in its own `try` block, so that one bad index does not stop the rest.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main() {
int n, q;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
cin >> q;
for (int k = 0; k < q; k++) {
int i;
cin >> i;
try {
cout << v.at(i) << endl;
} catch (const out_of_range& e) {
cout << "bad index " << i << endl;
}
}
return 0;
}