Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Help on vector says of front()

Returns a reference to the first element in the vector container. Unlike member vector::begin, which returns an iterator to this same element, this > function returns a direct reference.

Help on vector says of begin()

Returns an iterator referring to the first element in the vector container. Notice that unlike member vector::front, which returns a reference to the first element, > this function returns a random access iterator.

And this code outputs:

char arr[] = { 'A', 'B', 'C' };
vector<char> vec(arr, arr+sizeof(arr));
cout << "address of vec.front() " << (void*)&vec.front() << endl;
cout << "address of vec.begin() " << (void*)&vec.begin() << endl;

address of vec.front() 00401F90 address of vec.begin() 0030F494

I don't understand what 'direct reference' means? In the case of begin() isn't a random access iterator just a pointer?

Can someone please point out the difference?

like image 875
Angus Comber Avatar asked Oct 11 '12 13:10

Angus Comber


People also ask

What is front in vector?

vector::front()This function can be used to fetch the first element of a vector container.

What type is vector begin ()?

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 a begin iterator and an end iterator?

begin: Returns an iterator pointing to the first element in the sequence. cend: Returns a const_iterator pointing to the past-the-end element in the container. end: Returns an iterator pointing to the past-the-end element in the sequence.

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

In vector, each element only requires the space for itself only. In list, each element requires extra space for the node which holds the element, including pointers to the next and previous elements in the list.


1 Answers

According to Stroustrup in The C++ Programming Language, Section 16.3.3; think of front() as the first element and begin() as a pointer to the first element.

like image 195
bn. Avatar answered Sep 21 '22 13:09

bn.