Level 31
Level 31

Reputation: 403

How to use vectors efficiently?

I am using vectors and vector size_type in my code.

#include <iostream>
#include <vector>

using namespace std;
using std::vector;

typedef vector<int>::size_type size_type;

int main()
{
    size_type n; 
    cin>>n;
    vector<int> u(n,0);
    for(size_type i = 0; i != n; ++i) {
      cin >> u[i];
    }
    cout << *u.end();

    return 0;
}

The bug is that when I input n=5. The vectors asks for 5 elements and then prints out 0 or some garbage value. How do I print the last element?

Upvotes: 2

Views: 172

Answers (4)

rems4e
rems4e

Reputation: 3172

u.end() is an iterator that can't be dereferenced (so called "past the end iterator"). Use u.back() to get the last value.

Upvotes: 12

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

As it was already pointed thiis statement

cout<<*u.end();

results in printing the garbage value. The iterator returned by member function end() "points" to after the last actual element in the container.

It is the same as in the loop

for(size_type i=0; i!=n; ++i)

where the value of n is excluded from the loop. You could rewrite the loop the following way

for ( std::vector<int>::iterator it = u.begin(); it != u.end(); ++it )

In fact u.end() is equal to u.begin() + nIf n is not an acceptable index then u.begin() + nis not an iterator that may be dereferenced.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The bug is here:

cout<<*u.end();

The end() iterator points to the element one past the end of the vector. Dereferencing it is always undefined behavior.

If you have an end() iterator and you wish to see the last element, use std::prev, like this:

cout << *std::prev(u.end());

Upvotes: 5

Mike Seymour
Mike Seymour

Reputation: 254431

u.end() gives an iterator pointing beyond the last element; you'd have to decrement it to point to the last element. You can't dereference the past-the end iterator; trying to do so gives undefined behaviour.

The last element is available as u.back().

Upvotes: 3

Related Questions