矢量::空()是一个库函数“载体”头,它是用来检查给定的矢量是否是一个空的载体或没有,它返回一个真,如果矢量大小为0,否则返回假。
注意:要使用向量,请包含<vector>标头。
vector :: empty()函数的语法
vector::empty();
参数: void –不接受任何参数。
返回值:布尔-它返回真,如果矢量大小为0,否则返回假。
示例
Input: vector<int> vector1{ 1, 2, 3, 4, 5 }; vector<int> vector2; Function call: cout << vector1.empty() << endl; cout << vector2.empty() << endl; Output: false true
//C ++ STL程序演示示例 //vector :: empty()函数 #include <iostream> #include <vector> using namespace std; int main(){ vector<int> v1; //打印向量的大小 cout << "Total number of elements: " << v1.size() << endl; //检查向量是否为空 if (v1.empty()) cout << "vector is empty." << endl; else cout << "vector is not empty." << endl; //推动元素 v1.push_back(10); v1.push_back(20); v1.push_back(30); v1.push_back(40); v1.push_back(50); //打印向量的大小 cout << "Total number of elements: " << v1.size() << endl; //检查向量是否为空 if (v1.empty()) cout << "vector is empty." << endl; else cout << "vector is not empty." << endl; return 0; }
输出结果
Total number of elements: 0 vector is empty. Total number of elements: 5 vector is not empty.
参考:C ++ vector :: empty()