All submissions

Array Access Out of Bounds

#include <iostream>
#include <stdexcept>
#include <vector>
using namespace std;

// your code here: define getValue(const vector<int>& arr, int idx)
int getValue(const vector<int>& arr, int idx) {
    if (idx >= arr.size()) {
        throw std::out_of_range("Index out of range");
    }
    return arr[idx];
}

int main() {
   int n;
   cin >> n;
   vector<int> arr(n);
   for (int i = 0; i < n; i++) cin >> arr[i];
   int idx;
   cin >> idx;
   try {
       int value = getValue(arr, idx);
       cout << "Value: " << value << "\n";
   } catch (const out_of_range& e) {
       cout << "Error: " << e.what() << "\n";
   }
   return 0;
}
Loading...

Input

5 10 20 30 40 50 2

Expected Output

Value: 30