C++映射 empty()函数用于检查映射集合是否为空。如果映射集合为空(大小为0),则返回true,否则返回false。
bool empty() const;//until C++ 11 bool empty const noexcept; //since C++ 11
没有
如果映射集合为空(大小为0),则返回true,否则返回false。
让我们看一个简单的示例,以检查映射是否包含任何元素。
#include <map> #include <iostream> using namespace std; int main() { map<int,int> numbers; cout << " Initially, numbers.empty(): " << numbers.empty() << "\n"; numbers[1] = 100; numbers[2] = 200; numbers[3] = 300; cout << "\n After adding elements, numbers.empty(): " << numbers.empty() << "\n"; }
输出:
Initially, numbers.empty(): 1 After adding elements, numbers.empty(): 0
在上面的示例中,map的初始大小为0,因此,empty()函数返回1(true),添加元素后返回0(false)。
让我们看一个简单的示例,检查map是否为空。
#include <iostream> #include <map> using namespace std; int main(void) { map<char, int> m; if (m.empty()) cout << "Map is empty." << endl; m['n'] = 100; if (!m.empty()) cout << "Map is not empty." << endl; return 0; }
输出:
Map is empty Map is not empty
在上面的示例中,使用了 if 条件语句。如果map为空,则添加元素后将返回map为空。它将返回map不为空。
让我们看一个简单的例子。
#include <iostream> #include <map> using namespace std; int main () { map<char,int> mymap; mymap['x']=100; mymap['y']=200; mymap['z']=300; while (!mymap.empty()) { cout << mymap.begin()->first << " => " << mymap.begin()->second << '\n'; mymap.erase(mymap.begin()); } return 0; }
输出:
x => 100 y => 200 z => 300
在上面的示例中,它只在'while'循环中使用empty()函数并打印map的元素,直到map不为空。
让我们看一个简单的例子。
#include <iostream> #include <map> #include <string> using namespace std; int main() { typedef map<string, int> phoneMap; string name; int number; phoneMap phone; if (phone.empty()) cout << "Map is empty. Please insert content! \n " << endl; cout<<"Enter three sets of name and number: \n"; for(int i =0; i<3; i++) { cin>> name; //Get key cin>> number; //Get value phone[name] = number; //Put them in map } if (!phone.empty()) { cout<<"\nList of telephone numbers: \n"; phoneMap::iterator p; for(p = phone.begin(); p!=phone.end(); p++) { cout<<(*p).first << " " <<(*p).second <<" \n "; } } return 0; }
输出:
Map is empty. Please insert content! Enter three sets of name and number: Nikita 555555 Nidhi 111111 Deep 333333 List of telephone numbers: Deep 333333 Nidhi 111111 Nikita 555555
在上面的示例中,程序首先使用三个名称交互式创建电话映射。然后,它检查映射是否为空。如果映射为空,则显示一条消息,否则显示映射中所有可用的名称及其电话号码。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-map-empty-function.html
来源:LearnFk无涯教程网
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)