C++映射 size()函数用于查找映射集合中存在的元素数。
成员类型 size_type 是无符号整数类型。
size_type size() const;//until C++ 11 size_type size() const noexcept; //since C++ 11
它返回映射中存在的元素数。
让我们看一个简单的示例来计算映射的大小。
#include <map> #include <iostream> using namespace std; int main() { map<int,char> num {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}}; cout << "num map contains " << num.size() << " elements.\n"; }
输出:
num map contains 4 elements.
在上面的示例中,映射num包含4个元素。因此,size()函数返回4个元素。
让我们看一个简单的示例,计算映射的初始大小和添加元素后的映射大小。
#include <iostream> #include <map> using namespace std; int main(void) { map<char, int> m; cout << "Initial size of map = " << m.size() << endl; m = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5}, }; cout << "Size of map after inserting elements = " << m.size() << endl; return 0; }
输出:
Initial size of map = 0 Size of map after inserting elements = 5
在上面的示例中,第一个映射为空。因此,size()函数将返回0,在插入5个元素后将返回5。
让我们看一个简单的例子。
#include <iostream> #include <map> using namespace std; int main () { map<char,int> mymap; mymap['x']=100; mymap['y']=200; mymap['z']=300; while (mymap.size()) { cout << mymap.begin()->first << " => " << mymap.begin()->second << '\n'; mymap.erase(mymap.begin()); } return 0; }
输出:
x => 100 y => 200 z => 300
在上面的示例中,它仅在while循环中使用size()函数并打印map的元素,直到map的大小为止。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-map-size-function.html
来源:LearnFk无涯教程网
让我们看一个简单的例子。
#include <iostream> #include <map> #include <string> using namespace std; int main() { typedef map<string, int> phoneMap; string name; int number; phoneMap phone; 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 } cout<<"\nSize of phone map is:"<< phone.size(); 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; }
输出:
Enter three sets of name and number: Nikita 1001 Deep 2001 Aashi 3001 Size of phone map is:3 List of telephone numbers: Aashi 3001 Deep 2001 Nikita 1001
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)