1

I've a quite simple question but for witch I cannot find the answer.

How can I use the .at(i) in a 2D array of vector < vector <type> > ?

I want to have bounds checking - witch .at(i) function provides automatically, but I can only access my array using the array[i][j] witch doesn't provide for bounds checking.

1
  • It's a vector of vectors. Just substitute [...] by .at(...). How else should it work? Commented Oct 10, 2011 at 15:43

3 Answers 3

4

The correct syntax to use is:

array.at(i).at(j)
Sign up to request clarification or add additional context in comments.

1 Comment

You are right. I had tried that for starters but made other mistake and didn't complite, so I tought that was the problem.
3

Since .at(i) will return a reference to the vector at v[i], use .at(i).at(j).

2 Comments

You are right. I had tried that for starters but made other mistake and didn't compile, so I tough that was the problem. Thanks.
Reading compiler errors is in equal parts skill and art ... good luck :-)
2

Use vec.at(i).at(j) and must use this in try-catch block since at() will throw std::out_of_range exception if the index is invalid:

try
{
      T & item = vec.at(i).at(j);
}
catch(const std::out_of_range & e)
{
     std::cout << "either index i or j is out of range" << std::endl;
}

EDIT:

As you said in the comment:

I actually want the program to stop in case the exception is raised. – jbssm 5 mins ago

In that case, you can rethrow in the catch block after printing the message that it went out of range, so that you can know the reason why it stopped. And here is how you rethrow:

catch(const std::out_of_range & e)
{
     std::cout << "either index i or j is out of range" << std::endl;
     throw; //it rethrows the excetion
}

3 Comments

Thank you. I actually want the program to stop in case the exception is raised.
In that case, you can rethrow in the catch block after printing the message that it went out of range, so that you can know the reason why it stopped.
In that case, don't try/catch at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.