0

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:

  • vec1.[vec1.end() - 1][1]
  • vec1.[vec1.at(vec1.end()) - 1][1]

How can I use at when there are 2 dimensions?

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

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Toma
  • 163
  • 1
  • 10
  • 2
    at() operator checks for vector bounds as vector documentations explains.. – Manoel Stilpen Jun 02 '18 at 02:22
  • 2
    The `begin` and `end` functions returns *iterators* and not indexes. The iterators can not be used as indexes. Not to mention you use the member-access operator `.` to access the overloaded `[]` operator, which is wrong. It seems to me that you could use [a few good books to read](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). From the beginning. – Some programmer dude Jun 02 '18 at 02:23
  • 1
    `at` throws an `out_of_range` exception if the index is out of range. `[]` does not. – jspcal Jun 02 '18 at 02:23
  • For using at operator with two dimensional vectors you can call vec1.at(2).at(1) for example – Manoel Stilpen Jun 02 '18 at 02:24
  • `vec1.size()-1` is what you want. That's an index to the last vec1 entry. – doug Jun 02 '18 at 02:58

2 Answers2

3

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.
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0
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.

rsy56640
  • 299
  • 1
  • 3
  • 13