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