A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/vector-empty-in-cpp-stl/ below:

Vector empty() in C++ STL

Vector empty() in C++ STL

Last Updated : 21 Nov, 2024

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:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {11, 23, 45, 9};

    // Check if the vector is empty
    if (v.empty()) {
        cout << "Empty";
    } else {
        cout << "Not empty";
    }

    return 0;
}

This article covers the syntax, usage, and common examples of the vector empty() method in C++ STL, along with some interesting FAQs.

Syntax of Vector empty()

The vector empty() is defined inside std::vector class defined inside <vector> header file.

v.empty();

Parameter:

Return Value:

Examples of Vector empty()

The below example demonstrate the practical use of vector empty() method:

Check if a Vector is Empty C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v;

    if (v.empty()) {
        cout << "Empty";
    } else {
        cout << "Not Empty";
    }

    return 0;
}
Safely Accessing the First Element of the Vector C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {11, 23, 45, 9};

  	// Checking whether a vector is empty before using
  	// vector front() method
    if (!v.empty()) {
        cout << v.front();
    } else {
        cout << "Vector is empty";
    }

    return 0;
}

Explanation: Calling vector back() on an empty vector causes undefined behaviour. To prevent this, vector empty() is used.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4