我正在尝试解决Codeforces中的136A-Presents问题。尝试输入第二个输入时,我的程序崩溃了。这是我第一次使用地图进行编码。我的代码出了什么问题?
#include <map>
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
unsigned n; // number of friends
scanf("%u", n);
unsigned f[n]; // array of numbered friends
for(int c = 0; c < n; c++)
scanf("%u", f[c]); // getting input that tells you, for each friend to whom he gave a gift.
map<unsigned, unsigned> friends; // a map of friends, mapped by their digits and given numbers.
for(int i = 0; i < n; i++)
friends[f[i]] = i+1;
// ^ ^
// input indexes from 1 to n
/* Since keys are already sorted in the map, there is no need to re-sort them again. */
for(int j = 0; j < n; j++){
printf("%u", friends[j]); // printing values of keys.
if(j != n-1)
printf(" ");
}
return 0;
}
答案 0 :(得分:0)
我认为以这种方式使用地图是可以的,但是如果我正确地阅读了您的评论,您可能会将价值和关键字反转。请记住,如果密钥不是唯一的,那么您执行的方式只会更改您尝试添加多次的任何密钥的值,而不是创建另一个密钥。但是,scanf
需要指向类型对应于格式字符串的对象的指针,并且您甚至不会声明数组f
的类型。如果您有一些非标准编译器可以识别,或者您正在定义,unsigned as unsigned int,那么请尝试:
scanf("%u", &n);
scanf("%u", &f[c]);