C ++ map <k,t>初始化</k,t>

时间:2012-05-09 06:44:56

标签: c++ stl map variable-assignment

我正在阅读&#34; Ivor Horton的开始编程Visual C ++ 2010&#34;,以及我在第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)
}

指示的行是我的问题。我知道words是地图,但我从未见过这样的初始化。随着它的增量,那件事情又发生了什么。我相信Ivor Horton未能进一步阐述这一点,或者至少他应该给予足够大的介绍,不要让像我这样的新手感到惊讶。

2 个答案:

答案 0 :(得分:5)

你有这样一张地图:

sts::map<std::string, int> m;

访问运算符[key]为您提供了使用该键存储的元素的引用,或者如果它不存在则插入一个元素。所以对于一张空地图,这个

m["hello"];

在地图中插入一个条目,键为“Hello”,值为0.它还返回对该值的引用。所以你可以直接增加它:

m["Bye"]++;

会在键“Bye”下插入一个值0并将其递增1,或者将现有值递增1。

至于[]运算符中发生的事情,

*begin++

是一种递增istream_iterator并在增量前取消引用该值的方法:

begin++;

递增begin并返回增量前的值

*someIterator

取消引用迭代器。

答案 1 :(得分:1)

他一次做两件事,一般比他需要的更聪明。

  1. 他正在获取迭代器指向的值,然后递增迭代器。因此,将*begin++解释为*(begin++)。但是请注意,它是一个后增量,因此在取消引用后会发生增量。

  2. 他正在递增地图中给定键的值。取消引用迭代器时,会得到一个字符串。此字符串用作words地图的关键字,其值会增加。

  3. 传播更多行,看起来像这样:

    std::string x = *begin;
    begin++;
    words[x] += 1;
    
相关问题