×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

vector::empty() function with example in C++ STL

C++ STL vector::empty() function: Here, we are going to learn about the empty() function of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 13, 2019

C++ vector::empty() function

vector::empty() is a library function of "vector" header, it is used to check whether a given vector is an empty vector or not, it returns a true if the vector size is 0, otherwise it returns false.

Note: To use vector, include <vector> header.

Syntax

Syntax of vector::empty() function

vector::empty();

Parameter(s)

void – It accepts nothing as a parameter.

Return value

bool – It returns true if the vector size is 0, otherwise it returns false.

Sample Input and Output

Input:
vector<int> vector1{ 1, 2, 3, 4, 5 };
vector<int> vector2;

Function call:
cout << vector1.empty() << endl;
cout << vector2.empty() << endl;

Output:
false
true

C++ program to demonstrate example of vector::empty() function

//C++ STL program to demonstrate example of
//vector::empty() function

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v1;

    //printing the size of the vector
    cout << "Total number of elements: " << v1.size() << endl;
    //checking whether vector is empty or not
    if (v1.empty())
        cout << "vector is empty." << endl;
    else
        cout << "vector is not empty." << endl;

    //pushing elements
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);

    //printing the size of the vector
    cout << "Total number of elements: " << v1.size() << endl;
    //checking whether vector is empty or not
    if (v1.empty())
        cout << "vector is empty." << endl;
    else
        cout << "vector is not empty." << endl;

    return 0;
}

Output

Total number of elements: 0
vector is empty.
Total number of elements: 5
vector is not empty.

Reference: C++ vector::empty()

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.