0
我有一个代码,我在C++中反向迭代映射。对于地图中的n对,有时地图打印n对,有时n-1对。 测试用例在C++中反向迭代映射丢失了第一个元素
4 2
2 1
3 5
2 3
1 5
它打印4喜的,在接下来的情况下,3喜的
4 1
0 2
0 3
3 5
0 6
我的代码:
include cmath, cstdio, vector, iostream, map, algorithm, using namespace std;
int main() {
int n,f;
cin >> n >> f;
int k[n],l[n],dif[n];
map<int,int> m;
map<int,int>::reverse_iterator it;
for (int i=0;i<n;i++){
scanf("%d %d\n",&k[i],&l[i]);
dif[i] = l[i]-k[i];
m.insert(make_pair(dif[i],l[i]));
}
int a = 0;
int sum = 0;
for(it = m.rbegin(); it != m.rend(); ++it) {
cout << "hi" << endl;
int article = it->second - it->first;
int people = it->second;
if (a < f and article!=0){
a++;
if (2*article > people){
sum = sum + people;
} else {
sum = sum + (2*article);
}
} else {
if (article > people){
sum = sum + people;
} else {
sum = sum + article;
}
}
}
cout << sum;
return 0;
}
您可能想要'multimap'而不是'map'。 – Bernard