使用迭代器输出vector里面的元素

追求适度,才能走向成功;人在顶峰,迈步就是下坡;身在低谷,抬足既是登高;弦,绷得太紧会断;人,思虑过度会疯;水至清无鱼,人至真无友,山至高无树;适度,不是中庸,而是一种明智的生活态度。

导读:本篇文章讲解 使用迭代器输出vector里面的元素,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

最小的K个数_牛客题霸_牛客网 (nowcoder.com)

使用迭代器输出vector里面的元素 核心代码解答

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        int n=input.size();
        vector<int>ans;
        if(n<k)
        {
            return ans;
        }
        sort(input.begin(),input.end());
        for(int i=0;i<k;i++)
        {
            ans.push_back(input[i]);//使用push_back(),将input[i]加到容器里面
        }
        return ans;
    }
};

 acm模式解答

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	vector<int>ans;
	int n,i,k,input[100010];
	cin>>n>>k;
	for(int i=0;i<n;i++)
	{
		cin>>input[i];
	}
	sort(input,input+n);
	for(int i=0;i<k;i++)
	{
		ans.push_back(input[i]);
	}
	vector<int>::iterator it;//使用迭代器输出vector里面的元素
	for(it=ans.begin();it!=ans.end();it++)
	{
		cout<<*it;//输出vector里面的元素
	}
}

迭代器的作用是用来访问容器(用来保存元素的数据结构)中的元素

如果是逆向输出 

	vector<int>::reverse_iterator it;
	for(it=ans.rbegin();it!=ans.rend();it++)
	{
		cout<<*it;
	}

使用迭代器输出vector里面的元素

或者是

1014-[NOIP2006]明明的随机数_2021秋季算法入门班第一章习题:模拟、枚举、贪心 (nowcoder.com) 

使用迭代器输出vector里面的元素

#include<iostream>
#include<set>
using namespace std;
int main()
{
    set<int>q;
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        int t;
        cin>>t;
        q.insert(t);
    }
    //sort(q.begin(),q.end());set自带排序
    cout<<q.size()<<endl;
    for(auto d:q)
    {
      cout<<d<<' ';  
    }
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/131423.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!