在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
有个列表,往里面添加内容,如果对象已存在,只更新其属性,否则添加新一项。 #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; } 运行结果:
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论