1
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;

pair<char[300],int> list[10000];

int main()
{
    char a[300],b[20000];
    int n;
    cin >> n;
    for(int d=1; d<=n; d++)
    {
        list[d].second = 0;
    }
    int k=0;
    for(int d=1; d<=n; d++)
    {
        cin >> a;
        bool masuk=false;
        for(int e=1; e<=k;e++)
        {
            if (strcmp (a,list[e].first) == 0) 
            {
                masuk = true;
                list[e].second++;
                break;
            }
        }
        if (!(masuk))
        {
            k++;
            strcpy(list[k].first,a);
            list[k].second++;
        }
        cin.getline(b,256);
    }
    sort(list+1,list+k+1);
    for(int e =1; e<=k; e++)
    {
        cout << list[e].first << " " << list[e].second << endl;
    }
}

如果我输入

3
Spain Donna Elvira
England Jane Doe
Spain Donna Anna

我希望它输出

England 1
Spain 2

但它输出

Spain 2
England 1

不是 sort 假设先排序吗?但它似乎不起作用。我在 Dev C++ 上尝试了这个并且它输出正确,但是当在 ideone 上尝试这个时它输出错误

请帮助我,对不起我的英语不好。

4

2 回答 2

3

这里有几件事打败了我:

  1. 为什么要使用 std::pair 数组来模拟 std::map 的行为?
  2. 为什么你从 1 而不是 0 开始索引?

无论如何,正如 Max Lybbert 已经提到的,std::sort 需要第三个参数。该参数是指向排序函数的指针。这个适用于您的情况:

bool mysort(std::pair<const char*, int> a, std::pair<const char*,int> b) {
    return (strcmp(a.first, b.first) < 0);
}
于 2011-12-10T06:14:14.483 回答
2

我很惊讶您没有收到编译器错误。 std::sort不知道如何比较数组中的元素。您需要将该信息作为std::sort的第三个参数(作为指向函数的指针或作为仿函数)传递。

于 2011-12-10T06:06:00.183 回答