我使用地图的程序在第一次输入后崩溃

My program that uses maps crashes after first input

我正在尝试在 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;
}

我认为这样使用地图是可以的,但如果我正确阅读了您的评论,您可能会将值和键颠倒过来。请记住,如果键不是唯一的,那么您的操作方式只会更改您尝试多次添加的任何键的值,而不是创建另一个键。但是,scanf 需要一个指向类型对应于格式字符串的对象的指针,而您甚至没有声明数组 f 是什么类型。如果你有一些非标准编译器识别,或者如果你正在定义,unsigned as unsigned int,那么试试:

scanf("%u", &n);
scanf("%u", &f[c]);