【问题标题】:How can I pass a map by reference in C++?如何在 C++ 中通过引用传递地图?
【发布时间】:2021-11-28 10:44:12
【问题描述】:
#include<bits/stdc++.h>
#include<map>
using namespace std;
bool greaterThanExists(int i,std::map<int,int>&mpp)
{
    for(auto it:mpp)
    {
        if(it.first>i && it.second>0)
        {   cout<<it.first<<endl<<endl;
            it.second--;
            return true;
        }
    }
    return false;
}

int main()
{   int n;
    cin>>n;
    map<int,int>mpp;
    for(int i=0;i<n;i++)
    {
    int x;
    cin>>x;
    mpp[x]++;
    }
    int i=0;
    while(greaterThanExists(i,mpp))
    i++;
    
    // cout<<i<<endl;
    return 0;
}

问题:https://codeforces.com/contest/1165/problem/B

在 Codeforces 的这个问题中,我试图通过 C++ 中的引用传递地图,但显然这些更改并未反映在地图中。

【问题讨论】:

    标签: c++ reference hashmap c++17 pass-by-reference


    【解决方案1】:

    那是因为您正在迭代每个元素的副本:

    for(auto it:mpp)
    

    it 是一个副本。您需要迭代对元素的引用,而不是副本。所以改用这个:

    for (auto& it : mpp)
    

    永远记住auto 永远不会绑定到引用。即使您分配给auto 变量的对象是一个引用,auto 也会忽略它,除非您明确编写auto&amp;。

    【讨论】:

    • 非常感谢..问题已解决
    【解决方案2】:

    同意 Nikos C 的观点,你想迭代地图的引用而不是副本。这是另一种遍历地图的方法,可能更容易阅读:

    bool greaterThanExists(int i,std::map<int,int>&mpp)
    {
        for(auto& [key,val]:mpp)
        {
            if (key>1 && val>0)
            {
                cout<<key<<endl<<endl;
                val--;
                return true;
            }
        }
        return false;
    }
    

    【讨论】:

    • 非常感谢..这也很好用。
    猜你喜欢
    • 2017-12-04
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2010-12-24
    相关资源
    最近更新 更多