Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ stl what does base() do

Tags:

c++

vector

erase

I have such code :

vector <int> v; for (int i=0; i<5; i++)         v.push_back(i); v.erase(find(v.rbegin(), v.rend(),2).base()); 

This code deletes the first element from vector v after first detected 2 (in vector remain: 0 1 2 4). What does .base() do here?

like image 258
Vitali K Avatar asked May 17 '13 12:05

Vitali K


People also ask

What is iterator base?

The base iterator refers to the element that is next (from the std::reverse_iterator::iterator_type perspective) to the element the reverse_iterator is currently pointing to. That is &*(rit. base() - 1) == &*rit.

What are the components of STL?

STL contains five kinds of components: containers, iterators, algorithms, function objects and allocators.

Is C++ STL good?

The STL is great in that it was conceived very early and yet succeeded in using C++ generic programming paradigm quite efficiently. It separated efficiently the data structures: vector , map , ... and the algorithms to operate on them copy , transform , ... taking advantage of templates to do so.

What is STL briefly explain the use of containers vectors lists?

The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized.


1 Answers

base() converts a reverse iterator into the corresponding forward iterator. However, despite its simplicity, this correspondence is not as trivial as one might thing.

When a reverse iterator points at one element, it dereferences the previous one, so the element it physically points to and the element it logically points to are different. In the following diagram, i is a forward iterator, and ri is a reverse iterator constructed from i:

                             i, *i                              |     -      0     1     2     3     4     -                        |     |                         *ri   ri 

So if ri logically points to element 2, it physically points to element 3. Therefore, when converted to a forward iterator, the resulting iterator will point to element 3, which is the one that gets removed in your example.

The following small program demonstrates the above behavior:

#include <iostream> #include <vector> #include <iterator> #include <algorithm>  int main(int argc, char *argv[]) {     std::vector<int> v { 0, 1, 2, 3, 4 };     auto i = find(begin(v), end(v), 2);      std::cout << *i << std::endl; // PRINTS 2      std::reverse_iterator<decltype(i)> ri(i);     std::cout << *ri << std::endl; // PRINTS 1 } 

Here is a live example.

like image 147
Andy Prowl Avatar answered Oct 04 '22 12:10

Andy Prowl