zoukankan      html  css  js  c++  java
  • 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;
    }

     运行结果:

  • 相关阅读:
    函数定义、调用
    条件语句和循环语句
    eclipse中安装pydev插件出现duplicate location
    编码类型
    除法
    数据类型
    命令和python模式转换
    前言
    SpringMVC_json
    解决eclipse中Tomcat服务器的server location选项不能修改的问题
  • 原文地址:https://www.cnblogs.com/mjk961/p/9458809.html
Copyright © 2011-2022 走看看