0%

Type deduction in C++ Range-Base Loop

自從C++11有了auto和decltype之後,整個coding style有了很大的改變
現在我們有一個字串統計的map,該怎麼走訪這個map才好

1
map<string, int> wordCount;

pre-C++11

沒別招了

1
2
3
4
for (map<string, int>::iterator it = wordCount.begin();
it != wordCount.end(); ++it) {
// do something
}

雖然可以用typename簡化map<string, int>::iterator不過大同小異,看起來也不怎麼美觀

C++11

auto被賦予了新生命,於是可以寫出這樣的程式碼

1
2
3
for (auto &p : wordCount) {
// do something
}

C++17引進了structure binding進一步簡化

C++17

1
2
3
for (auto &[word, count] : wordCount) {
// do something
}