如何正确访问地图值?

问题描述 投票:0回答:1

我试图解决Leetcode问题#697:数组的度。我创建了一个地图来存储

<int, int>
值。我看到一些例子,人们使用
element.first
element.second
线来检索存储在地图中的值。但是,我收到一条错误消息,指出地图中没有名为
second
的成员。我想知道是否有内置函数可以从地图中检索第二个元素,以及是否有标准方法可以做到这一点。

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        
        //nums -> array of integers
        // step 1 : iterate through the array and find the degree, I would do this by iterating through nums and storing the value of each number in a hashmap
        // The hash map will store the number, first occ and last occ
            // The key will be the number and the values stored will be first and sec occurance.

        
        unordered_map<int,int> firstOcc;
        unordered_map<int,int> secondOcc;
        unordered_map<int,int> count;

        // Go through the array and collect the first/last occ and the frequency
        for (int i =0; i<nums.size(); i++)
        {   
            int currNum = nums[i];
            //If we've never come across this number before, update the first position.
            if(count[i]==0)
            {
                firstOcc[currNum] = i;
            }

            count[currNum]++;
            secondOcc[currNum] = i;
        }

        //Iterate through the count map and find the highest count.
        int highestCount =0;
        for (auto& i : count)
        {
            if (count.second > highestCount)
            {
                highestCount=count[i];
            }
        }

        //Now go through and figure out which has the shortest length
        int minLength = 0;
        for (auto i :count)
        {
            if (count[i]==highestCount)
            {
                int length = secondOcc[i]-firstOcc[i]+1;
                minLength = min(minLength, length);
            }
        }

        return minLength;
    }
};

这里我试图检索存储在

y
地图中
count[x][y]
count
值。

if (count.second > highestCount)
{
     highestCount=count[i];
}

这是我得到的错误:

Line 33: Char 23: error: no member named 'second' in 'std::unordered_map<int, int>'
    33 |             if (count.second > highestCount)      
c++ hashmap unordered-map
1个回答
0
投票

您的代码中有几个错误。

在您的

nums
迭代循环中,
i
是向量索引,但您的
count
键是向量元素而不是向量索引,因此此表达式:

if(count[i]==0)

需要改成这样:

if(count[currNum]==0)

count
迭代循环中,
i
std::pair
的元素(键+值
count
),而不是
count
的键,所以这个表达式:

if (count.second > highestCount)

需要改成这样:

if (i.second > highestCount)

还有这个表情:

highestCount=count[i];

需要改成这样:

highestCount=i.second;

还有这个表情:

if (count[i]==highestCount)

需要改成这样:

if (i.second==highestCount)

还有这个表情:

int length = secondOcc[i]-firstOcc[i]+1;

需要改成这样:

int length = secondOcc[i.second]-firstOcc[i.second]+1;

© www.soinside.com 2019 - 2024. All rights reserved.