second last element of vector

Could anyone please tell me how to get the second last element of the vector since back() returns the last element

Thanks
vec.rbegin() - 1 returns an iterator to the second last element, as long as there is one.
Thanks filipe

I have tried to print the value of the second last vector element like this:

cout << "raw_contents = " << raw_contents.rbegin() - 1 << endl;

but it is giving me an error which is

1
2
error: no match for β€˜operator<<’ in β€˜std::operator<< [with _Traits = std::char_traits<char>](((std::basic_ostream<char, std::char_traits<char> >&)(& std::cout)), ((const char*)"raw_contents.back() = ")) << std::reverse_iterator<_Iterator>::operator-(typename std::iterator_traits<_Iter>::difference_type) const [with _Iterator = __gnu_cxx::__normal_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> >*, std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >](1l)’
Well, as I said, it returns an iterator to the element, not the element itself. You must dereference it:

*(vec.rbegin() - 1)

EDIT: actually, since it's a reverse iterator, I think it's +1 instead:

*(vec.rbegin() + 1)
Last edited on
it is working when I use it without the -1

 
*(vec.rbegin())


It does give me the last element but gives me a segmentation fault error when I use it with -1.

I am new to STL so dont know much. Please help.
YES it worked with +1

MANY THANKS :)
Topic archived. No new replies allowed.