vector sort自定义比较函数

6325阅读 0评论2009-12-30 jiangwen127
分类:C/C++

#include 
#include 
#include 
using namespace std;

typedef struct _pair
{
    string word;
    int index;
}ST_PAIR;

vector dictionary;
vector storage;

class cmp
{
public:
    bool operator() (const ST_PAIR &a, const ST_PAIR &b)
    {
        return a.word < b.word;
    }
};

int bin_search(int front, int rear, string &target)
{
    int mid;
    while (front <= rear)
    {
        mid = (front + rear) / 2;
        if (dictionary[mid].word == target)
            return mid;
        if (dictionary[mid].word > target)
            rear--;
        else
            front++;
    }
    return -1;
}

int main(int argc, char *argv[])
{
    int n, i, m, index;
    ST_PAIR pair;
    string english, chinese;
    while (EOF != scanf("%d", &n))
    {
        for (i=0 ; i        {
            cin >> english >> chinese;
            pair.word = english;
            storage.push_back(chinese);
            pair.index = i;
            dictionary.push_back(pair);
        }
        sort(dictionary.begin(), dictionary.end(), cmp());
        vector::iterator iter;
        vector::iterator end = dictionary.end();
        /* search */
        cin >> m;
        for (i=0 ; i        {
            cin >> english;
            index = bin_search(0, n, english);
            if (-1 == index)
                cout << "I can't find out this word" << endl;
            else
                cout << storage[index] << endl;
        }
        dictionary.clear();
        storage.clear();
    }
}
上一篇:what I am, intersting
下一篇:linux查看硬件信息