C++ STL 中的 map::size()


在本文中,我們將討論 C++ STL 中 map::size() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 Map?

對映是關聯容器,它便利於儲存由鍵值和對映值組成的元素,並且按照特定順序儲存。在對映容器中,資料在內部始終透過其關聯鍵排序。對映容器中的值可透過其唯一鍵訪問。

什麼是 map::size()?

map::size() 函式是 C++ STL 中的一個內建函式,它在以下檔案中進行定義 header file. size() is used to check the size of the map container. This function gives size or we can say gives us the number of elements in the map container associated.

語法

map_name.size();

引數

此函式不接受任何引數。

返回值

此函式返回對映容器中的元素數量。如果容器沒有值,則該函式返回 0。

示例

輸入

std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b’, 20});
mymap.insert({‘c’, 30});
mymap.size();

輸出

3

輸入

std::map<int> mymap;
mymap.size();

輸出

0

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_1;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   cout<<"Size of TP_1 is: "<<TP_1.size();
   return 0;
}

輸出

Size of TP_1 is: 4

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_1;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   auto size = TP_1.size();
   auto temp = 1;
   while(size!=0) {
      temp = temp * 10;
      size--;
   }
   cout<<"Temp value is: "<<temp<<endl;
   return 0;
}

輸出

Temp value is: 10000

更新於: 15-4-2020

7K+ 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.