Toma
Toma

Reputation: 171

c++ [] with vector< vector<int> >

I'm having trouble with accessing elements of the last vector that is contained within a vector.

std::vector<std::vector<int>> vec1 = {{1,2,3}, {1,2,3}, {1,2,3}, {1,2,3}}.

How to get the second element of the last element of vec1 ?
I try:

How can I use at when there are 2 dimensions?

please explain the use of [] and .at().

Upvotes: 0

Views: 673

Answers (2)

rsy56640
rsy56640

Reputation: 309

void test()
{
    std::vector<std::vector<int>> vec1 = { { 1,2,3 },{ 1,2,3 },{ 1,2,3 },{ 1,2,3 } };
    int last_sec = *(++(--vec1.end())->begin());
}

to access the second element of the last element of vec1, you can use --end() to get the last iterator of the vec1, and ++(it->begin()) return the second iterator of it, then dereference to get the element.

std::vector:operator[] return type& without bound checking.
std::vector::at() Returns a reference to the element at specified location pos, with bounds checking.

Upvotes: 0

Jarod42
Jarod42

Reputation: 218248

With back, you might simply do:

vec1.back()[1];

instead of vec1.[vec1.size() - 1][1].

or even the iterator way:

(*(vec1.end() - 1))[1]; // or (vec1.end() - 1)->at(1);

please explain the use of [] and .at().

at does bound checking contrary to operator [] or back.

So for bound checking, use at instead of above alternative:

vec1.at(vec1.size() - 1).at(1); // std::out_of_range thrown is case of out of bound access.

Upvotes: 3

Related Questions