Home
Aptitude
Categories


Home » C++ STL

vector::front(), vector::back(), vector::at() and vector::data() functions with examples | C++ STL



In this article, we will learn about some of the most useful functions like vector::front(),vector::back(), vector::at() and vector::data() of vector class in C++ STL.
Submitted by IncludeHelp, on August 24, 2018

vector::front(), vector::back(), vector::at() and vector::data() functions are the predefined function of vector class, which are used for vector element accessing in C++ STL.

  1. vector::front()
    Returns reference to the first element of a vector i.e. we can say it returns first element of the vector.
  2. vector::back()
    Returns reference to the last element of a vector i.e. we can say it returns last element of the vector.
  3. vector::at(i)
    Returns reference to the ith element of a vector i.e. we can say it returns ith element of the vector.
  4. vector::data()
    As we know, vector is a dynamic array, and it can also be accessed like an array style. vector::data() returns the direct pointer to the first element of array (used by vector in the memory) and we can access all elements.

Example:

    Input:
    vector<int> num{10, 20, 30, 40, 50}

    Output:
    num.front(): 10
    num.back(): 50
    num.at(2): 30
    All elements using vector::data(): 10 20 30 40 50

Program:

#include <iostream>
#include <vector>

using namespace std;

int main() {
	//declare vector 
	vector<int> num{10, 20, 30, 40, 50};

	//vector::front ()
	cout<< "num.front(): " << num.front() <<endl;
	//vector::back ()
	cout<< "num.back() : " << num.back() <<endl;
	//vector::at ()
	cout<< "num.at(2) : " << num.at(2) <<endl;
	
	//vector::data ()
	int *ptr = num.data();
	cout<< "All elements using vector::data () : ";
	//note: there is no need to use vector iterator 
	for( int i =0; i<num.size(); i++)
		cout<< *(ptr+i) << " ";
	
	cout<<endl;

	return 0;
}

Output

    num.front(): 10
    num.back() : 50
    num.at(2) : 30
    All elements using vector::data () : 10 20 30 40 50 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.