C++学习笔记——并不是所有迭代器都有加减法

能进行算术运算的迭代器只有随即访问迭代器,要求容器元素存储在连续内存空间里,vector,string,deque的迭代器是有加减法的,但是map,set,multimap,multiset的迭代器是没有加减法的,list也不可以
该知识点是在刷leetcode347题时想到的

Given a non-empty array of integers, return the k most frequent
elements. For example, Given [1,1,1,2,2,3] and k = 2, return [1,2].

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k)
    {
        map<int,int> A;
        multimap<int,int> B;
        vector<int> C;
        for(int i=0;i<nums.size();i++)
        {
            ++A[nums[i]];
        }
        for(auto m=A.begin();m!=A.end();m++)
        {
            cout<<m->first<<m->second;
            B.insert(make_pair(m->second,m->first));
        }
        int u=0;
        auto n=--B.end();
        while(u!=k)
        {
            C.push_back(n->second);
            u++;
            n--;
        }
        return C;
    }
};

在最后对B进行遍历赋值的时候,错写成

 for(auto n=B.end()-1;n>=B.end()-1-k;--n)
 {
    C.push_back(n->first);
 }

map等的迭代器不支持加减操作,仅有++itr,–itr这些操作来进行选择

猜你喜欢

转载自blog.csdn.net/laoma023012/article/details/52199608
今日推荐