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

     运行结果:

  • 相关阅读:
    sql 大数据量 的分表操作
    NHibernate 2.0 配置
    NHibernate 之调用存储过程
    k-v-o 扫盲
    320学习笔记 2
    GCD之dispatch queue
    使用KVO体会
    timer,runloop,thread,task小总结
    Run Loop
    iPh oto的删除动画
  • 原文地址:https://www.cnblogs.com/mjk961/p/9458809.html
Copyright © 2020-2023  润新知