vectors

Hi,
when we have a vector, like below, can we consider always that cout<<*v.end()
will print 0 value? Can we find there some garbage value or not?

1
2
3
4
5
  int x{1,2,3,4,5}
  vector<int>v(x, x+5);
  cout<<*v.end();
  vector<int>v1(7);
  cout<<*v1.end();
can we consider always that cout<<*v.end()
will print 0 value?
end() returns [a kind of] pointer beyond the end of the vector. It will lead to undefined behavior to dereference this pointer.

Can we find there some garbage value or not?
Yes.
Use rbegin(), crbegin() for iterator access to the last element or back() for direct access to the last element of the vector:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5};
    std::cout << *(v.rbegin()) << "\n";
    std::cout << *(v.crbegin()) << "\n";
    std::cout << v.back() << "\n";
}
Topic archived. No new replies allowed.