C++ vector操作--往列表中添加或更新内容

有个列表,往里面添加内容,如果对象已存在,只更新其属性,否则添加新一项。

#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;
}

 运行结果:

 

posted @ 2018-08-11 10:47  niokit  阅读(3085)  评论(0编辑  收藏  举报