C++ map size() 函数

C++ map size() 函数

C++ map size() 函数用于查找 map 容器中元素的个数。

语法

成员类型 size_type 是一个无符号整数类型。

size_type size() const; // until C++ 11
size_type size() const noexcept; //since C++ 11

参数

返回值

返回地图中元素的数量

示例1

让我们看一个简单的示例来计算地图的大小。

#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.

在上面的示例中,map num 包含4个元素。因此,size() 函数返回4个元素。

示例2

让我们看一个简单的示例来计算 map 的初始大小和添加元素后的大小。

#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。

示例3

让我们看一个简单的示例。

#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的大小。

示例4

让我们看一个简单的示例。

#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

在上面的示例中,程序首先通过交互方式创建了一个包含三个姓名的电话映射。然后,它显示了电话映射的总大小以及映射中可用的所有姓名和电话号码。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程