[英]STL MAP should use find() or [n] identifier to find element in map?
我很困惑哪個更有效率?
由於我們可以直接訪問地圖,為什么我們需要使用find?
我只需要知道哪種方式更有效。
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
map<char,int>::iterator it;
mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;
//one way
it=mymap.find('b');
cout << (*it).second <<endl;
//another way
cout << mymap['b'] <<endl;
return 0;
}
提前致謝! :)
使用find
意味着如果密鑰不存在,您不會無意中在地圖中創建新元素,並且 - 更重要的是 - 這意味着如果您擁有的是一個常量,則可以使用find
來查找元素參考地圖。
那當然意味着你應該檢查find
的返回值。 通常情況如下:
void somewhere(const std::map<K, T> & mymap, K const & key)
{
auto it = mymap.find(key);
if (it == mymap.end()) { /* not found! */ }
else { do_something_with(it->second); }
}
由於我們可以直接訪問地圖,為什么我們需要使用find?
因為map<>::operator[]
有時很討厭。 如果元素不存在則:
因此,它總是返回有效的值引用,即使先前沒有鍵。 此行為不打算多次。
另一方面, map<>::find()
更安全; 因為它返回end()
,如果值沒有退出。 find()
另一個優點是它返回一個迭代器,它包含對key( first
)和value( second
)的引用。
map中的[]運算符不是常數,而是對數。 大多數書都強調這一事實,並指出它有點誤導。 因此,find和[]運算符具有相同的復雜性。
請注意,即使它不存在,[]運算符也會創建該條目,而在這種情況下,find將返回end()。
此代碼和文檔是從cplusplus.com中選取的
// accessing mapped values
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main ()
{
map<char,string> mymap;
mymap['a']="an element";
mymap['b']="another element";
mymap['c']=mymap['b'];
cout << "mymap['a'] is " << mymap['a'] << endl;
cout << "mymap['b'] is " << mymap['b'] << endl;
cout << "mymap['c'] is " << mymap['c'] << endl;
cout << "mymap['d'] is " << mymap['d'] << endl;
cout << "mymap now contains " << (int) mymap.size() << " elements." << endl;
return 0;
}
OP:
mymap['a'] is an element
mymap['b'] is another element
mymap['c'] is another element
mymap['d'] is
mymap now contains 4 elements.
注意最后一次訪問(到元素'd')如何在該映射中使用該鍵插入新元素並初始化為其默認值(空字符串),即使只訪問它以檢索其值。 成員函數map :: find不會產生這種效果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.