[C++] STL sort erase auto push_back

第16章 算法与映射 课后简单习题 vector部分1.~7.

自己写的课后题答案

CODE

#include 
#include 
#include 
#include 
#include "std_lib_facilities.h"

using namespace std;

struct Item {
public:
    string name;
    int iid;
    double value;
    
    Item(string s, int i, double v)
        : name{s}, iid{i}, value{v} {}

    
    friend ostream& operator<<(ostream& ost, const Item& item) 
    {
        return ost << item.name << " " << item.iid << " " << item.value << endl;    
    }

};

struct Cmp_by_name {
    bool operator()(const Item& a, const Item& b) 
    {   return a.name < b.name; }
};

struct Cmp_by_iid {
    bool operator()(const Item& a, const Item& b)
    {   return a.iid < b.iid;   }
};

struct Cmp_by_value{
    bool operator()(const Item& a, const Item& b)
    {   return a.value > b.value; }
};

void print(string info, vector& vi) 
{
    cout << info << " : "<< endl;
    for(Item & t : vi) 
        cout << t;
}

int main()
{
    vector vi;
    
    string iname = "item.txt";
    ifstream is {iname};
    
    string name;
    int iid;
    double value;
    while(is >> name >> iid >> value) {
        Item item {name, iid, value};
        vi.push_back(item);
    }
    
    print("ordinary vector", vi);
    
    sort(vi.begin(), vi.end(), Cmp_by_name());
    print("sorted by name", vi);

    sort(vi.begin(), vi.end(), Cmp_by_iid());
    print("sorted by iid", vi);
            
    sort(vi.begin(), vi.end(), Cmp_by_value());
    print("sorted by value", vi);
    
    
    vi.push_back(Item("horse shoe",99,12.34));
    vi.push_back(Item("Canon S400", 9988,499.95));
    print("Insert new elements",vi);
    
    string name1 = "JJJ";
    string name2 = "III";
    for(auto p = vi.begin(); p < vi.end();++p)
    {
        if(p->name == name1)
            vi.erase(p); 
    }
    print("", vi);
    
    for(auto p = vi.begin(); p < vi.end();++p)
    {
        if(p->name == name2)
            vi.erase(p); 
    }
    print("", vi);
    
    int iid1 = 2;
    int iid2 = 3;
    for(auto p = vi.begin(); p < vi.end();++p)
    {
        if(p->iid == iid1)
            vi.erase(p);
    }
    print("", vi);
    
    for(auto p = vi.begin(); p < vi.end();++p)
    {
        if(p->iid == iid2)
            vi.erase(p);
    }
    print("", vi);
            
}

DATA 自己设置的数据文件

// file: item.txt
FFF  1  5.55 
KKK  2  9.99 
CCC  3  2.22 
DDD  5  3.33 
HHH  4  6.66 
III  6  7.77 
JJJ  8  8.88
AAA  7  0.00 
BBB  9  1.11 
EEE  0  4.44 

NOTE 笔记

  • 文件读取;
  • STL vector 插入、删除元素;
  • STL 排序 sort 函数对象,设置不同的排序规则 :
    1. Cmp_by_name 按照 name 排序
    2. Cmp_by_iid 按照 iid 排序
    3. Cmp_by_value 按照 value 排序

HEADER 本书配套的头文件

// std_lib_facilities.h
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

REF 参考

Programming -- Principles and Practice Using C++ (Second Edition)
http://www.stroustrup.com/Programming/
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

你可能感兴趣的:([C++] STL sort erase auto push_back)