vector::empty() and vector::size() in C++ STL

09 Jun, 2022
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. 
The empty() function is used to check if the vector container is empty or not.Syntax : 
vectorname.empty()
Parameters :
No parameters are passed.
Returns :
True, if vector is empty
False, Otherwise
Examples: 
Input  : myvector = 1, 2, 3, 4, 5
         myvector.empty();
Output : False

Input  : myvector = {}
         myvector.empty();
Output : True
Time Complexity – Constant O(1)
Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed.
CPP
// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <vector>using namespace std; int main(){    vector<int> myvector{};    if (myvector.empty())    {        cout << "True";    }    else {        cout << "False";    }    return 0;}
True
Application : Given a list of integers, find the sum of all the integers. 
Input  : 1, 5, 6, 3, 9, 2
Output : 26
Explanation -  1+5+6+3+9+2 = 26
Algorithm1. Check if the vector is empty, if not add the back element to a variable initialized as 0, and pop the back element. 2. Repeat this step until the vector is empty. 3. Print the final value of the variable.
CPP
// CPP program to illustrate// Application of empty() function#include <iostream>#include <vector>using namespace std; int main(){    int sum = 0;    vector<int> myvector{ 1, 5, 6, 3, 9, 2 };    while (!myvector.empty())    {        sum = sum + myvector.back();        myvector.pop_back();    }    cout << sum;    return 0;}
26
size() function is used to return the size of the vector container or the number of elements in the vector container.Syntax : 
vectorname.size()
Parameters :
No parameters are passed.
Returns :
Number of elements in the container.
Examples: 
Input  : myvector = 1, 2, 3, 4, 5
         myvector.size();
Output : 5

Input  : myvector = {}
         myvector.size();
Output : 0
Time Complexity – Constant O(1)
Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed.
CPP
// CPP program to illustrate// Implementation of size() function#include <iostream>#include <vector>using namespace std; int main(){    vector<int> myvector{ 1, 2, 3, 4, 5 };    cout << myvector.size();    return 0;}
5
Why is empty() preferred over size()empty() function is often said to be preferred over the size() function due to some of these points- 
empty() function does not use any comparison operators, thus it is more convenient to useempty() function is implemented in constant time, regardless of container type, whereas some implementations of size() function require O(n) time complexity such as list::size().
empty() function does not use any comparison operators, thus it is more convenient to use
empty() function is implemented in constant time, regardless of container type, whereas some implementations of size() function require O(n) time complexity such as list::size().
Application : Given a list of integers, find the sum of all the integers. 
Input  : 1, 5, 6, 3, 9, 2
Output : 26
Explanation -  1+5+6+3+9+2 = 26
Algorithm1. Check if the size of the vector is 0, if not add the back element to a variable initialized as 0, and pop the back element. 2. Repeat this step until the size of the vector becomes 0. 3. Print the final value of the variable.
CPP
// CPP program to illustrate// Application of size() function#include <iostream>#include <vector>using namespace std; int main(){    int sum = 0;    vector<int> myvector{ 1, 5, 6, 3, 9, 2 };    while (myvector.size() > 0) {        sum = sum + myvector.back();        myvector.pop_back();    }    cout << sum;    return 0;}
26
We are required to be careful while using size().
For example, consider the following program:
C++
#include <bits/stdc++.h>using namespace std; int main(){     // Initializing a vector of string type    vector<string> vec = { "Geeks", "For", "Geeks" };     for (int i = 0 ; i <= vec.size() - 1 ; i++)        cout << vec[i] << ' ';    return 0;}
Geeks For Geeks 
The above program works fine but now let us consider the following program:
C++
#include <bits/stdc++.h>using namespace std; int main(){     // Initializing a vector of string type    vector<string> vec = { "Geeks", "For", "Geeks" };     vec.clear();    for (int i = 0; i <= vec.size() - 1; i++)        cout << vec[i] << ' ';     cout << "Geeks For Geeks";    return 0;}
Output:
Segmentation Fault SIGEGV
By compiling the above program, we get Segmentation Fault (SIGSEGV) because the return type of size() is size_t which is an alias for unsigned long int.-> unsigned long int var = 0;-> cout << var – 1;  // This will be equal to 18446744073709551615-> vector<data_type> vec;-> cout << vec.size() – 1;  // This will also be equal to 18446744073709551615
so we are looping from i = 0 to i = 18446744073709551615 in the above program
Now consider the scenario where we are deleting elements from our initialized container and after a sequence of operations our container becomes empty and lastly, we are printing contents of our container using the above method. Definitely, it will lead to Segmentation Fault (SIGSEGV).
How to fix it?
It is advisable to typecast container.size() to integer type in order to avoid Segmentation Fault (SIGSEGV).
C++
#include <bits/stdc++.h>using namespace std; int main(){     // Initializing a vector of string type    vector<string> vec = { "Geeks", "For", "Geeks" };           // Clearing the vector      // Now size is equal to 0    vec.clear();             // Typecasting vec.size() to int    for (int i = 0; i < (int)vec.size() - 1; i++)        cout << vec[i] << ' ';     cout << "Geeks For Geeks";    return 0;} // This code is contributed by Bhuwanesh Nainwal
Geeks For Geeks
sunilpanda20022002
bhuwanesh
utkarshgupta110092
CPP-Library
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
vector erase() and clear() in C++
Substring in C++
C++ Classes and Objects
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
Virtual Function in C++
C++ Data Types
Templates in C++ with Examples