Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is std::vector::front() used for?

Tags:

c++

stl

vector

Sorry if this has been asked before, but I am wondering what the use of std::vector::front() is.

Is there a reason to use e.g. myvector.front() rather than myvector[0] or myvector.at(0)?

like image 522
Tim Avatar asked Jan 21 '10 17:01

Tim


People also ask

What does vector front do?

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

What is front function in C++?

The list::front() is a built-in function in C++ STL which is used to return a reference to the first element in a list container. Unlike the list::begin() function, this function returns a direct reference to the first element in the list container. Syntax: list_name.front()

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.

Why do we use vector instead of array?

Vector is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure.


2 Answers

Some of the generic algorithms that also work on lists use it.

This is an example of a general principle: if you provide accessors for all the semantics you support, not just the implementation you support, it is easier to write generically and therefore easier to reuse code.

like image 159
dmckee --- ex-moderator kitten Avatar answered Sep 22 '22 17:09

dmckee --- ex-moderator kitten


If the type of myvector changes to another data type that is not indexable, such as a list, you will not have to change code that accesses the front of the container.

like image 20
Anne Avatar answered Sep 22 '22 17:09

Anne