C++ vector操作--往列表中添加或更新内容
2018-08-11 10:47
441 查看
有个列表,往里面添加内容,如果对象已存在,只更新其属性,否则添加新一项。
运行结果:
#include <iostream> #include <string> #include <vector> using namespace std; struct test { char s; int score; }; void print_v1(vector<test> &res) { vector<test>::iterator it = res.begin(); for (; it != res.end(); ++it) { cout << "[" << it->s << "," << it->score << "]" << endl; } } void add(vector<test> &res, const test i) { vector<test>::iterator it2 = res.begin(); bool flag = false; for (; it2 != res.end(); ++it2) { if (it2->s == i.s) { it2->score += i.score; flag = true; } } if (!flag) res.push_back(i); } int main() { vector<test> res; struct test a1; a1.s = 'A'; a1.score = 20; struct test a2; a2.s = 'B'; a2.score = 40; struct test a3; a3.s = 'C'; a3.score = 35; res.push_back(a1); res.push_back(a2); res.push_back(a3); print_v1(res); struct test i1; i1.s = 'D'; i1.score = 55; struct test i2; i2.s = 'A'; i2.score = 60; add(res, i1); add(res, i2); cout << "------------" << endl; print_v1(res); system("pause"); return 0; }
运行结果:
相关文章推荐
- javascript操作两个选择列表(有两个列表,如何实现在一个列表通过双击和多选列表中内容添加到另一个列表. )
- C++中关于文本内容的实用操作集合(新)(添加一些关于文件流的介绍)
- 用vector、 multimap、 list容器实现好友列表的各种操作 C++
- 用vector、 multimap、 list容器实现好友列表的各种操作 C++
- C++ vector的初始化、添加、遍历、插入、删除、查找、排序、释放操作
- 列表之间内容相互移动,列表添加元素
- C++中对Mysql的操作函数可以参考以下blog中的内容
- android操作sdcard中的多媒体文件(二)——音乐列表的更新
- 在csdn的blog中添加音乐列表(版本代码更新)
- Android - 分享内容 - 添加一个简单的分享操作
- SilverLight使用WCF RIA SERVICE实现对数据库的操作 (添加,删除,更新)
- 稳扎稳打Silverlight(57) - 4.0通信之WCF RIA Services: 概述, 通过 DomainDataSource 实现数据的添加、查询、更新和删除操作
- 稳扎稳打Silverlight(57) - 4.0通信之WCF RIA Services: 概述, 通过 DomainDataSource 实现数据的添加、查询、更新和删除操作
- 一步步学习SPD2010--第三章节--处理列表和库(16)----给内容类型添加文档模板
- C# 对sharepoint 列表的一些基本操作,包括添加/删除/查询/上传文件给sharepoint list添加数据
- VECTOR的常用操作(更新)
- ubuntu如何添加源和更新软件列表
- C++头文件有关内容(不断更新)
- C++ 算法库(2) 修改内容的序列操作