operator[]
Completed
Write class SafeArray wrapping a vector, whose operator[] clamps out-of-range indexes to the nearest valid one. Read an array and queries; print the element for each query index.
Input
n, the integers, q, then q indexes.
Output
q lines.
Example
Input
4 10 20 30 40 4 0 3 -5 99
Output
10 40 10 40
Editor
C++
Hints
operator[] takes the index as its parameter.
Solution explanation
Overloading [] lets a class look like an array while adding its own rules.
Show solution
#include <iostream>
#include <vector>
using namespace std;
class SafeArray {
public:
explicit SafeArray(vector<int> data) : data_(data) {}
int operator[](int i) const {
if (i < 0) i = 0;
if (i >= (int) data_.size()) i = (int) data_.size() - 1;
return data_[i];
}
private:
vector<int> data_;
};
int main() {
int n, q;
cin >> n;
vector<int> v(n);
for (int &x : v) cin >> x;
SafeArray a(v);
cin >> q;
for (int i = 0; i < q; i++) {
int idx;
cin >> idx;
cout << a[idx] << "\n";
}
return 0;
}