如何在循环中的 STL 映射中插入值

How to insert values in STL map within a loop

本文关键字:映射 插入 STL 循环      更新时间:2023-10-16

我想知道如何在循环中的map中插入值。我在以下代码中使用了insert(),但这不起作用。

#include<stdio.h>
#include<map>
#include<utility>
using namespace std;
int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        int n, i;
        map<char*, int> vote;
        char name[20], v;
        scanf("%d", &n);
        for (i = 0; i<n; ++i)
        {
            scanf("%s %c", name, &v);
            vote.insert(make_pair(name, 0));
            vote[name] = 0;
            if (v == '+')
                vote[name]++;
            else
                vote[name]--;
            printf("%dn", vote[name]);
            printf("Size=%lun", vote.size());
        }
        int score = 0;
        for (map<char*, int>::iterator it = vote.begin(); it != vote.end(); ++it)
        {
            printf("%s%dn", it->first, it->second);
            score += it->second;
        }
        printf("%dn", score);
    }
}

每次我键入新键(字符串)时,它只会更新前一个键。地图的大小始终为 1。

如何正确向地图添加新元素?

地图由指针 ( char* ) 键控。代码中的键始终是相同的 - name指针(尽管您更改了指针指向的内容,但它不会更改指针本身不相同的事实)。

您可以使用std::string而不是char*作为键。

更改地图的定义(替换 std::string 中的 char* )将解决此问题。

编辑:正如@McNabb所说,还将it->first更改为it->first.c_str()