51. Array Access Out of Bounds

Write a function getValue that safely accesses elements of an array:

  • int getValue(const vector<int>& arr, int idx)

If idx is invalid (negative or outside array size), throw std::out_of_range with the message:
 Index out of range

  • Otherwise, return the element at that index.

The program already creates a vector, calls getValue, and catches exceptions.
 You only need to implement the getValue function.
 

Example
 Input:

5
10 20 30 40 50
2

Output:

Value: 30

 

Input:

3
7 8 9
5

Output:

Error: Index out of range1
Loading...

Input

5 10 20 30 40 50 2

Expected Output

Value: 30