To check if a vector is empty in C++, you can use the empty()
member function, which returns true
if the vector contains no elements.
In this example,
numVec
to store numeric values.empty()
member function to check if numVec
is empty.numVec.empty()
returns true
, it means the vector is empty.#include <iostream>
#include <vector>
int main() {
std::vector<int> numVec;
if (numVec.empty()) {
std::cout << "Numeric vector is empty" << std::endl;
} else {
std::cout << "Numeric vector is not empty" << std::endl;
}
return 0;
}
Numeric vector is empty
In this example,
strVec
to store string values.empty()
member function to check if strVec
is empty.strVec.empty()
returns true
, it means the vector is empty.#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> strVec;
if (strVec.empty()) {
std::cout << "String vector is empty" << std::endl;
} else {
std::cout << "String vector is not empty" << std::endl;
}
return 0;
}
String vector is empty
In this tutorial, we learned How to check if a Vector is Empty in C++ language with well detailed examples.