Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between vector::begin() and std::begin()

Tags:

c++

vector

While iterating over a vector in c++, I noticed there is a begin() function in the standard library, and also a begin() as a member function of the vector class. What, if any, is the difference between the two, and which should be used over the other?

Example:

vector<int> numbers; //Code to put values in my vector for (vector<int>::iterator i = numbers.begin(); i < numbers.end(); i++)     cout << *i << '\n'; 

vs:

vector<int> numbers; //Code to put values in my vector for (vector<int>::iterator i = std::begin(numbers); i < std::end(numbers); i++)     cout << *i << '\n'; 
like image 832
Shadow Avatar asked Oct 10 '14 00:10

Shadow


People also ask

What is the difference between std::vector and vector?

Difference between std::vector and std::array in C++ As array is fixed size, once initialized can't be resized. Vector occupies more memory. Array is memory efficient data structure. Vector takes more time in accessing elements.

What does vector begin () do?

vector::begin() function is a bidirectional iterator used to return an iterator pointing to the first element of the container. vector::end() function is a bidirectional iterator used to return an iterator pointing to the last element of the container.

What is the difference between Begin and Cbegin in vector?

begin() returns an iterator to beginning while cbegin() returns a const_iterator to beginning. The basic difference between these two is iterator (i.e begin() ) lets you change the value of the object it is pointing to and const_iterator will not let you change the value of the object.

What does begin () mean in C++?

Introduction to C++ begin() This C++ begin() is used to get the iterator pointing to the initial element of the map container. This pointer is bidirectional since it can be moved to either directions in the sequence.


1 Answers

std::begin() was added in C++11 to make it easier to write generic code (e.g. in templates). The most obvious reason for it is that plain C-style arrays do not have methods, hence no .begin(). So you can use std::begin() with C-style arrays, as well as STL-style containers having their own begin() and end().

If you're writing code which is not a template, you can ignore std::begin(); your fellow programmers would probably find it odd if you suddenly started using it everywhere just because it's new.

like image 118
John Zwinck Avatar answered Sep 24 '22 00:09

John Zwinck