Joe*_*res 4 c++ stl map variable-assignment
我正在阅读"Ivor Horton的开始编程Visual C++ 2010",我在第10章 - 标准模板库.我的问题在于地图容器map<Person, string> mapname.这本书向我展示了很多添加元素的方法,比如稍后pair<K, T>使用和使用make_pair()函数,以及mapname.insert(pair).但突然他引入了以下代码中使用的元素添加技术:
int main()
{
std::map<string, int> words
cout << "Enter some text and press Enter followed by Ctrl+Z then Enter to end:"
<< endl << endl;
std::istream_iterator<string> begin(cin);
std::istream_iterator<string> end;
while(being != end) // iterate over words in the stream
//PROBLEM WITH THIS LINE:
words[*begin++]++; // Increment and store a word count
//there are still more but irrelevant to this question)
}
Run Code Online (Sandbox Code Playgroud)
指示的行是我的问题.我明白这words是地图,但我从未见过这样的初始化.随着它的增量,那件事发生了什么.我相信Ivor Horton没有进一步阐述这一点,或者至少他应该给予足够大的介绍,不要让像我这样的新手感到惊讶.
你有这样一张地图:
sts::map<std::string, int> m;
Run Code Online (Sandbox Code Playgroud)
访问运算符[key]为您提供对使用该键存储的元素的引用,或者如果它不存在则插入一个元素.所以对于一张空地图,这个
m["hello"];
Run Code Online (Sandbox Code Playgroud)
在地图中插入一个条目,键为"Hello",值为0.它还返回对该值的引用.所以你可以直接增加它:
m["Bye"]++;
Run Code Online (Sandbox Code Playgroud)
将在键"Bye"下插入值0并将其递增1,或将现有值递增1.
至于[]运营商内部发生的事情,
*begin++
Run Code Online (Sandbox Code Playgroud)
是一种在增量istream_iterator之前递增和取消引用值的方法:
begin++;
Run Code Online (Sandbox Code Playgroud)
递增begin并返回递增前的值
*someIterator
Run Code Online (Sandbox Code Playgroud)
取消引用迭代器.
| 归档时间: |
|
| 查看次数: |
873 次 |
| 最近记录: |