加快 C++ 代码性能(map、find()、输入和输出)

Speed up C++ code performance (map, find(), input and output)

我们将 pairs(a,b) 个值的 int 个值输入控制台序列。然后我们输入整数序列(z)。如果我们有一些 a[i] == z,应该输出 b[i].

    int main()
    {
        std::ios::sync_with_stdio(false);

        std::map<int, int> mp;
        std::map<int, int>::iterator iter;

        int x, y;
        while (std::cin >> x && x != -1 && std::cin >> y && y != -1) {
            mp[x] = y;
        }
        while (std::cin >> x && x != -1) {
            iter = mp.find(x);
            if (iter != mp.end())
                std::cout << iter->second << ' ';
            else
                std::cout << 0 << ' ';
        }
        std::cout << -1;
    }

代码不够快,请帮助我理解我需要做什么才能让它更快。


解决方案:实际上,问题出在"mp.find(x)"。只需要 "mp[x]" ...

您的代码中没有任何内容表明您需要排序地图。因此,使用 std::unordered_map,这通常比 std::map.

快得多

另请注意,一些认为 std::ios_base::sync_with_stdio(false); 重要的人添加了类似这样的内容:

std::cin.tie(nullptr);
std::cout.tie(nullptr);