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:
#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;
}
Output
Not empty
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:
- This function does not take any parameter.
Return Value:
- Returns true if the vector is empty.
- Returns false if the vector is not empty.
Examples of Vector empty()
The below example demonstrate the practical use of vector empty() method:
Check if a Vector is Empty
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v;
if (v.empty()) {
cout << "Empty";
} else {
cout << "Not Empty";
}
return 0;
}
Output
Empty
Safely Accessing the First Element of the Vector
#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;
}
Output
11
Explanation: Calling vector back() on an empty vector causes undefined behaviour. To prevent this, vector empty() is used.