transform,unique等方法的使用

测试记录一下以备忘。

实现的功能是从一个结构体类型的vector里,取其中某一个字段来生成一个新的vector,并去掉重复。

用库函数实现,代码量比较少。

VS2015 -- win32控制台:


#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;

struct stu
{
 char name[20];
 int age;
 int weight;
};

struct get_name
{
 explicit get_name() {}

 char* operator()(stu& stu_arg) const
 {
  return stu_arg.name;
 }
};

int main()
{


 vector<string> name_list;

 vector<stu> stu_list;
 stu s1 = { "大张", 20, 100 } ;
 stu s2 = { "sevn", 21, 110 };
 stu s3 = { "tom", 24, 120 };
 stu s4 = { "小何", 27, 121 };
 stu s5 = { "merry", 25, 105 };
 stu s6 = { "merry", 29, 115 };
 stu s7 = { "小何", 21, 123 };
 stu_list.push_back(s1);
 stu_list.push_back(s2);
 stu_list.push_back(s3);
 stu_list.push_back(s4);
 stu_list.push_back(s5);
 stu_list.push_back(s6);
 stu_list.push_back(s7);

 vector<string>::iterator it;

 transform(stu_list.begin(), stu_list.end(), back_inserter(name_list), get_name());

 for (it = name_list.begin() ; it != name_list.end(); it++)
 {
  cout << "name = " << (*it).c_str() << endl;
 }

 cout << "排序后:" << endl;
 sort(name_list.begin(), name_list.end());
 vector<string>::iterator it_earse = unique(name_list.begin(), name_list.end());

 name_list.erase(it_earse, name_list.end());

 for (it = name_list.begin(); it != name_list.end(); it++)
 {
  cout << "name = " << (*it).c_str()  << endl;
 }

 cout << "size:" << name_list.size() << endl;
 cout << "capacity:" << name_list.capacity() << endl;
    return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值