【STL】inserter和front_inserter的用法

#include <iostream> 
#include <algorithm> 
#include <list>  
using namespace std;  
int iArray[5] = { 1, 2, 3, 4, 5 }; 

void Display(list<int>& a, const char* s) 
{   
	cout << s << endl;   
	copy(a.begin(), a.end(),ostream_iterator<int>(cout, " "));   
	cout << endl; 
}

int main() 
{   
	list<int> iList;
	copy(iArray, iArray + 5, front_inserter(iList));   
	Display(iList, "Before find and copy"); 
	list<int>::iterator p = find(iList.begin(), iList.end(), 3);
	copy(iArray, iArray + 2, inserter(iList, p));   
	Display(iList, "After find and copy");    
	return 0; 
	
}  


 

Before find and copy
5 4 3 2 1
After find and copy
5 4 1 2 3 2 1
请按任意键继续. . .

 

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

class myclass
{
public:
	friend ostream &operator << (ostream &, const myclass &);
     myclass(int a,int b):first(a),second(b)
	 {
	 }
     int first;
     int second;
     bool operator < (const myclass &m) const 
     {
          return first < m.first;
     }     
}; 

//reload
ostream &operator << (ostream &out,const myclass &mc)
{
	out << mc.first << " " <<mc.second <<endl;
	return out;
}

bool less_second(const myclass &m1,const myclass &m2)
{
	return m1.second<m2.second;
}

void Display(vector<myclass> &v, const char* s)   
{     
    cout << endl << s << endl;     
    copy(v.begin(), v.end(),ostream_iterator<myclass>(cout," "));     
    cout << endl;   
}  


int main()
{
    int i=0;
    vector<myclass> vct;
    for(i=0;i<10;i++)
    {
            myclass my(10-i,i*3);
            vct.push_back(my);
    }
	Display(vct,"Initial");

    sort(vct.begin(),vct.end()); //按第1个值排序 

	Display(vct,"after sorted by the  first:");
    sort(vct.begin(),vct.end(),less_second);//按第2个值排序

	Display(vct,"after sorted by the  second: ");
    system("pause");           
    return 0;
}


 


Initial
10 0
 9 3
 8 6
 7 9
 6 12
 5 15
 4 18
 3 21
 2 24
 1 27


after sorted by the  first:
1 27
 2 24
 3 21
 4 18
 5 15
 6 12
 7 9
 8 6
 9 3
 10 0


after sorted by the  second:
10 0
 9 3
 8 6
 7 9
 6 12
 5 15
 4 18
 3 21
 2 24
 1 27

请按任意键继续. . .

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值