初始化我的std :: map

时间:2016-05-06 04:19:25

标签: c++ stl initialization

我编写了以下使用Map的代码。此程序会查找string密钥在Map中显示的次数。如果它只出现一次,则int键的string值应为1,依此类推。这个程序运行并产生所需的输出 - 但我觉得这是纯粹的运气,因为我不是在任何地方初始化地图。我正在做myMap[str]++ - 这绝不保证最初的价值是0。那么,在遇到string之前,我如何初始化地图以使任何0键的值为myMap[str]++

#include<cstdio>
#include<string>
#include<iostream>
#include<map>

int main()
{
    int t;
    long int n;
    std::string str;
    std::map< std::string, int > myMap;
    scanf("%d", &t);

    while(t--)
    {
        scanf("%ld", &n);
        std::cin.ignore();
        while(n--)
        {
            getline(std::cin, str);
            myMap[str]++;
        }

        for(std::map< std::string, int >::iterator it=myMap.begin(); it!=myMap.end(); it++)
            printf("%s %d\n", it->first.c_str(), it->second);
        printf("\n");

        myMap.erase(myMap.begin(), myMap.end());
    }

    return 0;
}

示例输入:

  

2
  6
  03 10103538 2222 1233 6160 0142
  03 10103538 2222 1233 6160 0141
  30 10103538 2222 1233 6160 0141
  30 10103538 2222 1233 6160 0142
  30 10103538 2222 1233 6160 0141
  30 10103538 2222 1233 6160 0142
  
  5
  30 10103538 2222 1233 6160 0144
  30 10103538 2222 1233 6160 0142
  30 10103538 2222 1233 6160 0145
  30 10103538 2222 1233 6160 0146
  30 10103538 2222 1233 6160 0143

示例输出:

  

03 10103538 2222 1233 6160 0141 1
  03 10103538 2222 1233 6160 0142 1
  30 10103538 2222 1233 6160 0141 2
  30 10103538 2222 1233 6160 0142 2
  
  30 10103538 2222 1233 6160 0142 1
  30 10103538 2222 1233 6160 0143 1
  30 10103538 2222 1233 6160 0144 1
  30 10103538 2222 1233 6160 0145 1
  30 10103538 2222 1233 6160 0146 1

详细的问题描述可以找到here

谢谢!

2 个答案:

答案 0 :(得分:5)

你说:

  

这绝不保证最初的值是0

这是不正确的。如果某个键对应的项目不在地图中,则在使用operator[]函数时会初始化该值。

来自http://en.cppreference.com/w/cpp/container/map/operator_at

  

如果执行插入,则映射的值是值初始化的(默认为类类型构造,否则为零初始化),并返回对它的引用。

换句话说,

        myMap[str]++;

是有效且正确的代码。

答案 1 :(得分:0)

您可以使用std::map::find()检查密钥是否已存在。如果存在,则对从find返回的迭代器指向的项执行增量。否则,你写myMap[str] = 0

   while(n--)
   {
        getline(std::cin, str);
        std::map< std::string, int >::iterator it = myMap.find(str);
        if( myMap.end() != it )
             (*it).second++;
        else
            myMap[str] = 1;
   }

然而,您的代码没问题,因为在您的代码中初始化了int。它只是不可见(std::pair<string,int>是默认构造的。)