我怎样才能优化代码?

时间:2017-07-13 09:34:41

标签: c++ algorithm dictionary optimization

我做出了问题的决定,但它并不适合。您还可以如何优化此代码(提高性能)。 <{1}}和int无法触及。

代码:

map

1 个答案:

答案 0 :(得分:0)

您可以通过删除队列来略微改进代码,但不需要这样 其余代码看起来算法最优。

#include <map>
#include <iostream>

using namespace std;

int main()
{
    int a,b;

    map<int, int> AB;
    map<int, int>::iterator it;

    std::ios::sync_with_stdio(false);

    while (1)
    {
        cin >> a;
        if (a == -1)break;
        cin >> b;
        AB.insert(pair<int, int>(a, b));
    }

    while (1)
    {
        cin >> a;

        if (a == -1) {
            cout << -1;
            return 0;
        }

        it = AB.find(a);
        if (it == AB.end())
            cout << 0 << " ";
        else
            cout << it->second << " ";
    }

    return 0;
}