[英]Pointer to a map
如果我像這樣定義一個指向map
的指針:
map<int, string>* mappings;
mappings
是一個指針。 我應該如何使用這個指針來操作地圖?
使用指針就像使用任何其他指針一樣:取消引用它以獲取它指向的對象。
typedef std::map<int, string>::iterator it_t;
it_t it1 = mappings->begin(); // (1)
it_t it2 = (*mappings).begin(); // (2)
string str = (*mappings)[0]; // (3)
請記住, a->b
基本上是等價於(*a).b
,然后玩得開心!
(盡管這種等價性不適用於像(*a)[b]
這樣的按索引訪問,您可能不使用->
語法。)
除了您必須使用->
訪問map
成員之外,沒有太大區別。 IE
mapping->begin() or mapping->end()
如果您對此感到不舒服,那么您可以為其分配一個引用並以自然的方式使用它:
map<int, string> &myMap = *mappings; // 'myMap' works as an alias
^^^^^^^^
myMap
使用myMap
。 IE
myMap[2] = "2";
myMap.begin() or myMap.end();
例如:
#include <map>
#include <string>
#include <iostream>
int main() {
std::map<int, std::string> * mapping = new std::map<int, std::string>();
(*mapping)[1] = "test";
std::cout << (*mapping)[1] <<std::endl;
}
隨着 c++ 11 中“at”函數的引入,您可以使用mappings->at(key)
而不是(*mapping)[key]
。
請記住,如果該鍵在地圖中不可用,則此 api 將拋出out_of_range
異常。
另一種使用指針的好方法,我喜歡調用 mappings->(以及你想調用的函數)
好吧,STL 旨在降低指針處理的復雜性..所以更好的方法是使用 stl::iterator.. 盡量避免指針:-/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.