EMPTY()
This functions is used to check whether a std::vector
contains no elements. It is a member function of the vector class and returns a boolean value: true
if the vector has no elements, and false
otherwise. This provides a convenient and readable way to determine if a vector is empty without comparing its size()
to zero. For example, calling vec.empty()
on a vector named vec
will return true
when vec
has no elements and false
when it contains one or more elements. This method is essential for safely performing operations on vectors, ensuring that functions like access or iteration are only done when the vector has content.
vectorName.empty();
* Returns true if the vector has no elements
* Returns false if the vector has at least one element
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Step 1: Declare an empty vector of strings
vector<string> tasks;
// Step 2: Check if the vector is empty
if (tasks.empty()) {
cout << "No tasks found!" << endl;
} else {
cout << "Tasks are available." << endl;
}
// Step 3: Add a task
tasks.push_back("Finish homework");
// Step 4: Check again
if (tasks.empty()) {
cout << "No tasks found!" << endl;
} else {
cout << "Tasks are available." << endl;
}
return 0;
}
OUTPUT:
No tasks found!
Tasks are available.
Last updated