leetcode ----Intersection of Two Arrays

思路:因为set容器不会有重复元素,找到后放到set中,然后再拷贝到vector中(注意copy 函数 比for在复制值的时候效率高!!)

vector<int> intersection(vector<int>& nums1, vector<int>& nums2) 
    {
        vector<int> res;
        set<int> tem;
        unordered_map<int,int> m;
        for(int i=0;i<nums1.size();i++)
        {
            m[nums1[i]]++;
        }
        for(int i=0;i<nums2.size();i++)
        {
            if(m[nums2[i]]>=1)
                tem.insert(nums2[i]);
        }
       copy(tem.begin(), tem.end(), inserter(res, res.begin())); 
        
        return res;
    }



std::copy cannot be used to insert into an empty container. To do that, you need to use an insert_iterator like so:

std::set<double> input;
input.insert(5);
input.insert(6);

std::vector<double> output;
std::copy(input.begin(), input.end(), inserter(output, output.begin()));




元素复制算法copy。该算法主要用于容器之间元素的拷贝,即将迭代器区间[first,last)的元素复制到由复制目 标result给定的区间[result,result+(last-first))中。下面我们来看看它的函数原型:

1     template<class InputIterator, class OutputIterator>  
2        OutputIterator copy(  
3           InputIterator _First,   
4           InputIterator _Last,   
5           OutputIterator _DestBeg  
6        );  

参数

_First, _Last
指出被复制的元素的区间范围[ _First,_Last).
_DestBeg 
指出复制到的目标区间起始位置

返回值

返回一个迭代器,指出已被复制元素区间的最后一个位置


copy和copy_backward函数的功能其实是一样的,无非是从第1个开始拷贝和从最后一个开始拷贝的区别。


先看一下这两个函数的参数:
copy(first,last,result);//first为容器的首迭代器,last为容器的末迭代器,result为结果数组。


copy_backward(first,last,result);//first为容器的首迭代器,last为容器的末迭代器,result为结果数组。


copy_backward 与 copy函数的不同之处在于:copy_backward函数它是从最后一个元素向前复制.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值