如何在循环中的 STL 映射中插入值
How to insert values in STL map within a loop
我想知道如何在循环中的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()
。
相关文章:
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- 如何编写用于多映射插入和擦除功能的 API?
- C++,映射插入&&文件流读取导致麻烦
- 多映射插入键类型信息 std::make_pair vs std::p air 构造函数
- 将一个映射插入到同一多重映射的另一个映射中会导致 SEG 错误
- 将元素插入 c++ 映射 - 插入方法的差异
- 使用boost::关联属性映射插入boost::BIMAP..失败
- STL 无序映射 - 插入到向量中
- C++在映射插入期间保证移动
- Visual Studio C++-std::映射插入失败
- C++映射插入
- 标准::映射插入/擦除的并发问题
- 不明确的映射.插入boost
- 无序映射插入复制元素
- 无序映射插入()错误
- 自定义键出现c++映射插入错误
- c++多映射插入两个以上的值
- 使用配对类型的映射插入
- 调试映射插入
- STL映射插入复制构造函数