C++ STL 中的 map::begin() 和 end()


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

什麼是 C++ STL 中的 Map?

Map 是關聯容器,它可以方便地儲存由鍵值和對映值組合而成的元素,並以特定的順序進行儲存。在 map 容器中,資料在內部始終透過其關聯的鍵進行排序。map 容器中的值可以透過其唯一的鍵進行訪問。

什麼是 map::begin()?

map::begin() 函式是 C++ STL 中的內建函式,它在 header file. begin() is used to access the element which is at the very beginning of the associated map container.

此函式返回一個迭代器,該迭代器指向容器的第一個元素。當容器中沒有值時,無法取消引用迭代器。

語法

map_name.begin();

引數

該函式不接受任何引數。

返回值

此函式返回一個迭代器,該迭代器指向 map 容器的第一個值。

示例

輸入

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

輸出

a:10

示例

 線上演示

#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<<"Elements of TP_1 after swap:\n"<< "\tKEY\tELEMENT\n";
   for (auto i = TP_1.begin(); i!= TP_1.end(); i++) {
      cout << "\t" << i->first << "\t" << i->second << '\n';
   }
   return 0;
}

輸出

Elements of TP_1 after swap:
KEY    ELEMENT
1       10
2       20
3       30
4       40

什麼是 map::end()?

map::end() 函式是 C++ STL 中的內建函式,它在 <map> 標頭檔案中定義。end() 用於訪問容器中最後一個元素之後的元素,或者最後一個元素之後的元素。

此函式返回一個迭代器,該迭代器指向容器中最後一個元素之後的元素。當容器中沒有值時,無法取消引用迭代器。

通常,begin() 和 end() 用於透過提供範圍來迭代 map 容器。

語法

map_name.end();

引數

該函式不接受任何引數。

返回值

此函式返回一個迭代器,該迭代器指向 map 容器最後一個值之後的元素。

示例

輸入

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

輸出

error

示例

 線上演示

#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<<"Elements of TP_1 after swap:\n"<< "\tKEY\tELEMENT\n";
   for (auto i = TP_1.begin(); i!= TP_1.end(); i++) {
      cout << "\t" << i->first << "\t" << i->second << '\n';
   }
   return 0;
}

輸出

Elements of TP_1 after swap:
KEY    ELEMENT
1       10
2       20
3       30
4       40

更新於: 2020年4月15日

671 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告