Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Vector empty() in C++ STL
Next article icon

Vector end() in C++ STL

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the vector end() is a built-in method used to obtain an iterator pointing to the theoretical element after the last element of the vector. Even though this iterator does not point to a valid element, it serves as a marker for the end of the vector.

Let’s take a look at an example that illustrates the use of the vector end() method:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v = {1, 3, 5, 2, 4};      	// Printing last element using vector end     cout << *(--v.end());      return 0; } 

Output
4

Explanation: As the iterator does not point to the last element. We have to decrement it to access the last element.

This article covers the syntax, usage, and common examples of the vector end() method in C++:

Table of Content

  • Syntax of Vector end()
  • Supported Iterator Operations
  • Examples of Vector end()
    • Iterator Over a Vector
    • Access Nth Last Element of Vector
    • Apply Sort Algorithm on Vector

Syntax of Vector end()

The vector end() is a member method of the std::vector class defined inside the <vector> header file.

v.pop_back();

This function neither takes any parameter nor returns any value.

Supported Iterator Operations

The vector end() returns a iterator of type vector::iterator which is a random-access iterators. So, it supports all the operations allowed in the iterator arithmetic in C++ i.e. dereferencing, incrementing/decrementing, adding/subtracting integers, subtraction of another iterator of same container, comparison.

But just like pointers, iterators may point to invalid memory location. So, before using them make sure that the iterator is valid.

Examples of Vector end()

The vector end() function is used in conjunction with vector begin() function to basically perform various operations on the vector using iterators. The below example illustrates how the vector end() is used in different scenarios for different purposes:

Iterator Over a Vector

C++
#include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v = {1, 3, 5, 2, 4};      // Use end() to iterate through the vector     for (auto it = v.begin(); it != v.end(); ++it)         cout << *it << " ";        return 0; } 

Output
1 3 5 2 4 

The iterator returned by vector begin() is increment and dereferenced till it is not equal to the vector end() iterator, which marks the end of the vector.

Access Nth Last Element of Vector

C++
#include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v = {1, 3, 5, 2, 4};   	int n = 2;      	// Access 2nd Element from last     cout << *(v.end() - n);      return 0; } 

Output
2

Explanation: As vector end() iterator points to the position after the last element, decreasing it once will make it point to the last element, twice to the second last element and so on.

Apply Sort Algorithm on Vector

C++
#include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v = {1, 3, 5, 2, 4};      	// Sort vector v using sort()     sort(v.begin(), v.end());      	for (auto i: v)       	cout << i << " ";     return 0; } 

Output
1 2 3 4 5 

Almost all the STL algorithms works on ranges defined by the iterators and the whole vector range is defined by vector begin() and end().



Next Article
Vector empty() in C++ STL

A

AyushSaxena
Improve
Article Tags :
  • C++
  • cpp-containers-library
  • cpp-vector
  • STL
Practice Tags :
  • CPP
  • STL

Similar Reads

  • Vector in C++ STL
    C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted. Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template
    8 min read
  • 8 Ways to Initialize Vector in C++
    Initializing a vector means assigning some initial values to the std::vector elements. In this article, we will learn 8 different ways to initialize a vector in C++. Table of Content Using Initializer ListOne by One InitializationWith a Single ValueFrom an ArrayFrom Another VectorFrom Any STL Contai
    5 min read
  • Commonly Used Methods

    • Vector end() in C++ STL
      In C++, the vector end() is a built-in method used to obtain an iterator pointing to the theoretical element after the last element of the vector. Even though this iterator does not point to a valid element, it serves as a marker for the end of the vector. Let’s take a look at an example that illust
      4 min read

    • Vector empty() in C++ STL
      In C++, vector empty() is a built-in method used to check whether the given vector is empty or not. In this article, we will learn about vector empty() method in C++. Let’s take a look at an example that illustrates the vector empty() method: [GFGTABS] C++ #include <bits/stdc++.h> using namesp
      2 min read

    • Vector operator[ ] in C++ STL
      In C++, the vector operator [] is used to randomly access or update the elements of vector using their indexes. It is similar to the vector at() function but it doesn't check whether the given index lies in the vector or not. Let’s take a look at a simple code example: [GFGTABS] C++ #include <bit
      3 min read

    • Vector front() in C++ STL
      In C++, the vector front() is a built-in function used to retrieve the first element of the vector. It provides a reference to the first element, allowing you to read or modify it directly. Let’s take a quick look at a simple example that uses the vector front() method: [GFGTABS] C++ #include <bi
      2 min read

    • Vector push_back() in C++ STL
      In C++, the vector push_back() is a built-in method used to add a new element at the end of the vector. It automatically resizes the vector if there is not enough space to accommodate the new element. Let’s take a look at an example that illustrates the vector push_back() method: [GFGTABS] C++ #incl
      2 min read

    • Vector insert() in C++ STL
      In C++, the vector insert() is a built-in function used to insert new elements at the given position in a vector. In this article, we will learn about the vector insert() function in C++. Let’s take a look at an example that shows the how to use this function: [GFGTABS] C++ #include <bits/stdc++.
      5 min read

    • vector emplace() in C++ STL
      In C++, vector emplace() is used to insert elements at the given position in a vector by constructing it in-place within the vector, rather than creating a temporary object and then moving or copying it into the vector. Let's take a quick look at a simple example that uses vector emplace() method: [
      4 min read

    • Vector assign() in C++ STL
      In C++, the vector assign() is a built-in method used to assign the new values to the given vector by replacing old ones. It also modifies the size of the vector according to the given number of elements. Let’s take a look at an example that shows the how to use this function. [GFGTABS] C++ #include
      4 min read

    • Vector erase() in C++ STL
      In C++, vector erase() is a built-in function that is used to delete elements from the vector. It removes an element of a specific position or range of elements from the vector. Let’s take a simple example that uses the vector erase() method: [GFGTABS] C++ #include <bits/stdc++.h> using namesp
      3 min read

    Other Member Methods

    • Vector max_size() in C++ STL
      In C++, vector max_size() is a built-in function used to find the maximum number of elements that can be held by the vector container. In this article, we will learn about the vector max_size() function in C++. Let's take a look at an example that illustrates this method: [GFGTABS] CPP #include <
      3 min read

    • Vector capacity() in C++ STL
      In C++, the vector capacity() is a built-in method used to find the capacity of vector. The capacity indicates how many elements the vector can hold before it needs to reallocate additional memory. In this article, we will learn about vector capacity() method in C++. Let’s take a look at an example
      3 min read

    • vector rbegin() and rend() Functions in C++ STL
      In C++, std::vector::rbegin() and std::vector::rend() are built-in functions used to retrieve reverse iterators to the reverse beginning and reverse end of a vector. These functions allow easy traversal of vectors in reverse i.e. from the last element to the first. They are the member functions of t
      3 min read

    • vector :: cbegin() and vector :: cend() in C++ STL
      Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. vector::cbegin() The function returns an iterator which is used to iterate container. The iterator points to the beginning of the vector.Iterat
      2 min read

    • Vector crend() in C++ STL
      In C++, the vector crend() is a built-in method used to obtain a constant reverse iterator pointing to the theoretical element just before the first element of the vector. It is used to mark the reverse end of the vector. Let’s take a look at an example: [GFGTABS] C++ #include <bits/stdc++.h>
      2 min read

    • Vector resize() in C++ STL
      In C++, the vector resize() is a built-in method used to change the size of vector container after it is declared. It can be used to increase or decrease the size of vector. Let’s take a look at an example that illustrates the vector resize() method: [GFGTABS] C++ //Driver Code Starts{ #include <
      3 min read

    • Vector shrink_to_fit() in C++ STL
      In C++, vector shrink_to_fit() is a built-in function used to reduce the capacity of the vector to fit its size and destroys all elements beyond the size. In this article we will learn about vector shrink_to_fit() in C++. Let’s take a quick look at an example that illustrates vector shrink_to_fit()
      2 min read

    • When to use Vector reserve() in C++?
      In a vector, when the number of elements to be inserted are greater than the current capacity, it is reallocated to a larger memory block and all the items are copied to this new block making this reallocation an expensive operation with time complexity of O(n). This mechanism works well if you don'
      2 min read

    • Vector data() in C++ STL
      In C++, the vector data() is a built-in function used to access the internal array used by the vector to store its elements. In this article, we will learn about vector data() in C++. Let’s take a look at an example that illustrates the vector data() method: [GFGTABS] C++ #include <bits/stdc++.h
      2 min read

  • 2D Vector in C++
    A 2D vector is a vector of the vector i.e. each element is a vector in itself. It can be visualised as a matrix where each inner vector represents a row, and the number of rows represents the maximum columns. A 2D vector is dynamically resizable in both dimensions. Let’s take a look at a simple illu
    6 min read
  • Passing Vector to a Function in C++
    To perform operations on vector belonging to one function inside other function, we pass this vector to the function as arguments during the function call. C++ provides three methods to pass a vector to a function in C++. Let's look at each of them one by one. Table of Content Pass Vector by ValuePa
    5 min read
  • How Does a Vector Internally Works in C++?
    In C++, a vector is a dynamic array that can resize itself when more elements are added or deleted. So, one may ask that how a vector internally works to achieve its dynamic resizing capability while maintaining similar efficiency to static arrays in operations? For vector to work as a resizable dyn
    5 min read
  • How to implement our own Vector Class in C++?
    The given task is to implement a class in C++ which behaves just like the Vector class.Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements a
    5 min read
  • Advantages of Vector Over Array in C++
    In C++, both vectors and arrays are used to store collections of elements, but vector offers significant advantages over arrays in terms of flexibility, functionality, and ease of use. This article explores the benefits of using vectors in C++ programming. The major advantages of vector over arrays
    3 min read
  • Common Vector Programs

    • Sorting a Vector in C++
      Sorting a vector means arranging the elements of vector in ascending order or in descending order or in desired defined order. In this article, we will learn about different ways to sort the vector in C++. The most efficient way to sort the vector is by using sort() method. Let’s take a look at an e
      3 min read

    • How to Reverse a Vector using STL in C++?
      Reversing the vector means the swapping last element and first element, second last element and second element, and so on. In this article, we will learn how to reverse a vector using STL in C++. The most efficient method to reverse the vector is by using reverse() function. Let’s take a look at a s
      3 min read

    • How to Find the Minimum and Maximum Element of a Vector Using STL in C++?
      In this article, we will learn how to find the minimum and maximum element in vector in C++. The simplest method to find the minimum and maximum element in vector is by using min_element() and max_element(). Let’s take a look at a simple example: [GFGTABS] C++ #include <bits/stdc++.h> using na
      2 min read

    • How to Find Index of a Given Element in a Vector in C++?
      Vectors stores elements in contiguous memory and these elements can be accessed by their indexes. In this article, we will learn the reverse process, i.e., finding the index of the given element in a vector in C++. The simplest way to find the index of the given element in the vector is by using fin
      3 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences