(六)C++中的類型轉(zhuǎn)換、IO流與STL標(biāo)準(zhǔn)模板庫

C++中的類型轉(zhuǎn)換與STL標(biāo)準(zhǔn)模板庫

一华望、C++類型轉(zhuǎn)換

在C++中類型轉(zhuǎn)換包含 static_cast、const_cast仅乓、dynamic_cast、reinterpret_cast 四種類型轉(zhuǎn)換蓬戚。使用原始類型轉(zhuǎn)換夸楣,所有轉(zhuǎn)換都是一種寫法,可讀性不高子漩,有可能有潛在的風(fēng)險

1豫喧、static_cast

該類型轉(zhuǎn)換函數(shù)用于不同類型的屬性之間的轉(zhuǎn)換

#include <iostream>
using namespace std;


void* func(){
    int i = 0;
    return &i;
}
void main(){
    //自動類型轉(zhuǎn)換
    //int i = 0;
    //double d = i;
    //或
    //double d = 9.5;
    //int i = d;
    
    // int i = 8;
    // double d = 9.5;
    // i = static_cast<int>(d);
    // cout << "i = " << i << endl;
    
    int i = 9;
    int *i_p = &i;
}

void* 轉(zhuǎn) char*

void* func(int type){
    switch(type){
        case 1:
            int i = 11;
            return &i;
        case 2:
            int a = 'X';
            return &a;
        default:
            return NULL;
    }
}
void main(){
   //void* 轉(zhuǎn) char*
   //char* c_p = (char*)func(2);
   char* c_p = static_cast<char*>(func(2));
   
   //C++
   
   func
   //C
}

2、const_cast

該類型轉(zhuǎn)換函數(shù)用于去常量幢泼,一般使用在常量屬性轉(zhuǎn)為非常量屬性時使用

void func(char c[]){
    //可以修改
    c[0] = 'H';
    c[1] = 'a';
}

void func2(const char c[]){
    //c[0] = 'H'; //不能修改
    //c[1] = 'a';//不能修改
    //通過指針間接賦值
    //其他人并不知道紧显,這次轉(zhuǎn)型是為了去常量
    //char* c_p = (char*)c;
    //c_p[1] = 'a';
    //cout << c << endl;
    
    //C++ 去常量,可讀性高
    char* c_p = const_cast<char*>(c);
    c_p[1] = 'y';
    cout << c << endl;
}

void main(){
    char c[] = "hello";
    func2(c);
    
    getchar();
}

3缕棵、dynamic_cast

該類型轉(zhuǎn)換用于父類對象轉(zhuǎn)換為子類時使用孵班,處理父類轉(zhuǎn)為子類時的不確定性(類型不匹配時轉(zhuǎn)型失敗涉兽,返回NULL)

class Person{
public:
    virtual void print(){
        cout << "人" <<endl;
    }    
};

class Man : public Person{
public:
    void print(){
        cout << "男人" <<endl;
    }
    void smoking(){
        cout << "吸煙" <<endl;
    }
};

class Woman : public Person{
public:
    void print(){
        cout << "女人" <<endl;
    }
    void makeup(){
        cout << "化妝" <<endl;
    }
};

void func(Person* obj){
    obj->print();
    //調(diào)用子類的特有函數(shù),需要轉(zhuǎn)為實際類型
    //當(dāng)傳入Woman對象時篙程,轉(zhuǎn)型為Man枷畏,轉(zhuǎn)型失敗,但是編譯器并為察覺
    //Man* man = (Man*)obj;
    //man->print();
      
    //轉(zhuǎn)型失敗虱饿,返回NULL  
   //Man* man = dynamic_cast<Man*>(obj);
    //man->print();
    Man* man = dynamic_cast<Man*>(obj);
    if(man!=NULL){
        man->smoking();
    }
    
    Woman* woman = dynamic_cast<Woman*>(obj);
    if(woman!=NULL){
        woman->makeup();
    }
    
    
}
void main(){
    Woman w1;
    //父類類型的指針指向子類對象
    Person* p = &w1;
    func(p);
    
    getchar();
}

4拥诡、reinterpret_cast

該類型轉(zhuǎn)換用于函數(shù)指針之間的轉(zhuǎn)型,在使用函數(shù)指針轉(zhuǎn)型時使用

void func1(){
    
}

char* func2(){
    return "abc";
}

typedef void(*f_p)();

void main(){
    f_p f_array[6];
    f_array[0] = func1;
    //C 方式
    f_array[1] = (f_p)func2;
    f_array[1] = reinterpret_cast<f_p>func2;

    
    getchar();
}

二氮发、IO 流

在 C++ 中渴肉,通過<fstream> 頭文件中的 ifstream 讀取文件,ofstream 寫入文件爽冕,完成 IO 流操作

1仇祭、文本文件操作

對于文本文件,可進(jìn)行使用 ifstream 中的 get(ch) 讀取一個字符扇售;使用 fout << 寫入一個字符串


#include <fstream>
void main(){
    char fname[] = "D://dest.text";
    //輸出流
    ofstream fout(fname);
    //創(chuàng)建失敗
    if(fout.bad()){
        return -1;
    }
    fout << "Jack" << endl;
    fout << "Rose" << endl;
    fout.close();
    
    //讀取
    ifstream fin(fname);
    if(fin.bad()){
        return -2;
    }
    char ch;
    while(fin.get(ch)){
        cout << ch;
    }
    fin.close();
}

2前塔、二進(jìn)制文件操作

對于二進(jìn)制文件,可進(jìn)行使用 ifstream中的read(buff,1024) 讀取二進(jìn)制文件承冰,通過 ofstream中的write(buff,1024) 寫入到對應(yīng)文件中


#include <fstream>
void main(){
    char src[] = "D://xueshan.jpg";
    char src_copy[] = "D://xueshan_copy.jpg";
     //讀取
    ifstream fin(src,ios::binary);
    
    //輸出流
    ofstream fout(src_copy,,ios::binary);
    //創(chuàng)建失敗
    if(fin.bad()||fout.bad()){
        return -1;
    }
    while(!fin.eof()){
        char buff[1024] = {0};
        fin.read(buff,1024);
        //寫入
        fout.write(buff, 1024);
    }
    //關(guān)閉
    fin.close();
    fout.close();
}

3华弓、對象持久化

class Person{
private:
    char* name;
    int age;
public:
    Person(){}
    Person(char* name,int age){
        this->name = name;
        this->age = age;
    }
    
    char* getName(){
        return this->name;
    }
    
    int getAge(){
        return this->age;
    }
    
    void print(){
        cout << this->name << "," << this->age << endl;
    }
};

void main(){
    Person p1(const_cast<char*>("Jack"),25);
    Person p2(const_cast<char*>("Rose"),22);
    //輸出流
    ofstream fout("D://c_obj.data",ios::binary);
    //指針能夠讀取到正確的數(shù)據(jù),讀取內(nèi)存區(qū)的長度
    fout.write((char*)(&p1), sizeof(Person));
    fout.write((char*)(&p2), sizeof(Person));
    fout.close();
    
    //輸入流
    ifstream fin("D://c_obj.data",ios::binary);
    Person tmp;
    fin.read((char*)(&tmp), sizeof(Person));
    tmp.print();
    
    fin.read((char*)(&tmp), sizeof(Person));
    tmp.print();
}

三困乒、STL(standard template library)標(biāo)準(zhǔn)模板庫

在 C++ 中包含很多標(biāo)準(zhǔn)模板庫寂屏,可以讓代碼更加簡潔

1、string 模板庫

使用 string 模板庫娜搂,在邊寫代碼時更改簡潔易用迁霎,但是在JNI中 string 需要轉(zhuǎn)為 char ,,在轉(zhuǎn)為jstring返回*

1.1 string 初始化

#include <string>
void main(){
    string s1 = "Hello ";
    string s2(" every day");
    string s3 = s1 + s2;
    cout << s3 << endl;
    
    //string 轉(zhuǎn) c 字符串,在JNI中要轉(zhuǎn)為C的str 然后再轉(zhuǎn)為jstring返回
    const char* c_str = s1.c_str();
    cout << c_str << endl;
}

1.2 string 遍歷

#include <string>
//string遍歷
void main()
{
    string s1 = "craig david";
    //           ^
    //1 數(shù)組方式
    for (int i = 0; i < s1.length(); i++)
    {
        cout << s1[i] << endl;
    }
    //2 迭代器指針
    for (string::iterator it = s1.begin(); it != s1.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
    //3 at函數(shù)(charAt)
    // 可能會拋出異常
    try
    {
        for (int i = 0; i < s1.length() + 3; i++)
        {
            cout << s1.at(i) << " ";
        }
    }
    catch (...)
    {
        cout << "異常" << endl;
    }


    system("pause");
}

1.3 string 字符串查找替換

#include <string>
#include <iostream>

using namespace std;
//字符串查找替換
void main()
{
    string s1 = "apple google apple iphone";
    //從0開始查找"google"的位置
    int idx = s1.find("google", 0);
    cout << idx << endl;

    //統(tǒng)計apple出現(xiàn)的次數(shù)
    int idx_app = s1.find("apple",0);
    //npos大于任何有效下標(biāo)的值
    int num = 0;
    while (idx_app != string::npos)
    {
        num++;
        cout << "找到的索引:" << idx_app << endl;
        idx_app+=5;
        idx_app = s1.find("apple", idx_app);
    }

    cout << num << endl;
    system("pause");
}

1.4 string 刪除(截劝儆睢)和插入

#include <string>
#include <iostream>

using namespace std;
//刪除(截瓤剂)和插入
void main()
{
    string s1 = "apple google apple iphone";
    //刪除a,找到a所在的指針
    string::iterator it = find(s1.begin(),s1.end(),'g');
    //只能刪除一個字符
    s1.erase(it);
    
    //開頭末尾插入字符串
    s1.insert(0, "macos");
    s1.insert(s1.length(), " facebook");

    cout << s1 << endl;
    system("pause");
}

1.5 string 大小寫轉(zhuǎn)換

#include <string>
#include <iostream>
#include <algorithm> //算法

using namespace std;
//java StringBuffer才可變
//String 不可變
//大小寫轉(zhuǎn)換
void main()
{
    string s1 = "JASON";
    //原始字符串的起始地址携御,原始字符串的結(jié)束地址, 目標(biāo)字符串的起始地址, 函數(shù)名稱
    transform(s1.begin(), s1.end()-1,s1.begin(), tolower);
    cout << s1 << endl;


    transform(s1.begin(), s1.end() - 1, s1.begin(), toupper);
    cout << s1 << endl;

    system("pause");
}

2昌粤、容器 vector 模板庫

使用 vector 模板庫,不需要使用動態(tài)內(nèi)存分配啄刹,就可以使用動態(tài)數(shù)組

2.1 vector 初始化與遍歷

#include <vector>

void printVector(vector<int> &v)
{
    //通過數(shù)組的方式遍歷
    for (int i = 0; i < v.size(); i++)
    {
        cout << v[i] << endl;
    }
}


void main(){
    //動態(tài)數(shù)組
    vector<int> v;
    v.push_back(12);
    v.push_back(118);
    v.push_back(1);
    v.push_back(52);
    v.push_back(20);
    //遍歷
    for(int i = 0; i<v.size(); i++){
        cout << v[i] << endl;
    }
    
    //部分復(fù)制
    vector<int> v3(v1.begin(),v1.begin()+2);
     for(int i = 0; i<v3.size(); i++){
        cout << v3[i] << endl;
    }
    
}

2.2 vector 添加和刪除

//添加 刪除
void main()
{
    //添加到結(jié)尾
    vector<int> v1;
    v1.push_back(20);
    v1.push_back(40);
    v1.push_back(15);
    v1.push_back(7);

    //訪問頭部
    v1.front() = 11;
    //訪問尾部
    v1.back() = 90;

    //刪除結(jié)尾的元素
    //v1.pop_back();
    while (v1.size() > 0)
    {
        cout << "末尾的元素:" << v1.back() << endl;
        v1.pop_back();
    }

    printVector(v1);

    system("pause");
}

2.3 vector 數(shù)組方式

//數(shù)組的方式
void main()
{
    vector<int> v1;
    v1.push_back(20);
    v1.push_back(40);
    v1.push_back(15);
    v1.push_back(7);

    v1[2] = v1[2] +10;

    //容器等價于動態(tài)數(shù)組 
    vector<int> v2(10);
    for (int i = 0; i < v2.size(); i++)
    {
        v2[i] = i + 1;
    }

    printVector(v2);

    system("pause");
}

2.4 vector 迭代器遍歷

//迭代器遍歷
//迭代器的種類(正向涮坐,反向迭代器)
void main()
{
    vector<int> v1;
    v1.push_back(20);
    v1.push_back(40);
    v1.push_back(15);
    v1.push_back(7);
    //正向
    for (vector<int>::iterator it = v1.begin(); it < v1.end(); it++)
    {
        cout << *it << endl;
    }
    cout << "-----------------" << endl;
    //反向迭代
    for (vector<int>::reverse_iterator it = v1.rbegin(); it < v1.rend(); it++)
    {
        cout << *it << endl;
    }

    system("pause");
}

2.5 vector 插入和刪除

void main()
{
    vector<int> v1(10);
    for (int i = 0; i < v1.size(); i++)
    {
        v1[i] = i + 1;
    }

    //刪除指定位置
    vector<int>::iterator it = v1.begin();
    it += 3;
    v1.erase(it);

    //distance(v1.begin(), it);

    //刪除區(qū)間
    v1.erase(v1.begin(), v1.begin() + 3);

    for (vector<int>::iterator it = v1.begin(); it < v1.end(); it++)
    {
        if (*it == 5)
        {       
            printf("%x\n", it);
            vector<int>::iterator tmp = v1.erase(it); //注意以后開發(fā)中編譯器版本問題
            printf("%x,%x\n",it,tmp);
        }
    }

    //插入
    v1.insert(v1.begin() + 2, 100);
    v1.insert(v1.end() - 1, 200);

    printVector(v1);

    system("pause");
}

3、隊列 deque 模板庫

3.1 雙向隊列


//雙向隊列
#include <deque>
void printDeque(deque<int>& q)
{
    for (int i = 0; i < q.size(); i++)
    {
        cout << q[i] << endl;
    }
}


void main()
{
    deque<int> d1;
    //添加到尾部
    d1.push_back(2);
    d1.push_back(10);
    //添加到頭部
    d1.push_front(-90);
    d1.push_front(-30);

    //printDeque(d1);

    //cout << d1.front() << endl;
    //cout << d1.back() << endl;

    //兩個方向彈出
    //d1.pop_back();
    //d1.pop_front();

    printDeque(d1);

    //查找第一個-90元素索引位置誓军,無需遍歷
    deque<int>::iterator it = find(d1.begin(), d1.end(), -90);
    if (it != d1.end())
    {
        int idx = distance(d1.begin(), it);
        cout << "索引位置為:" << idx << endl;
    }


    system("pause");
}

3.2 沒有迭代器的隊列

#include <iostream>
#include <queue>
using namespace std;
void main()
{
    queue<int> q;
    q.push(78);
    q.push(18);
    q.push(20);
    q.push(33);
    
    //q.front();
    //q.back();
    while (!q.empty())
    {
        int tmp = q.front();
        cout << tmp << endl;
        q.pop();
    }   
    system("pause");
}

3.3 優(yōu)先級隊列

#include <iostream>
#include <queue>
using namespace std;
void main()
{
    //默認(rèn) 最大值優(yōu)先級
    priority_queue<int> pq1;
    pq1.push(12);
    pq1.push(3);
    pq1.push(40);
    pq1.push(15);

    while (!pq1.empty())
    {
        int tmp = pq1.top();
        cout << tmp << endl;
        pq1.pop();
    }

    cout << "----------" << endl;
    //最小值優(yōu)先級隊列
    priority_queue<int, vector<int>, greater<int>> pq2;
    pq2.push(12);
    pq2.push(3);
    pq2.push(40);
    pq2.push(15);

    while (!pq2.empty())
    {
        int tmp = pq2.top();
        cout << tmp << endl;
        pq2.pop();
    }

    system("pause");
}

4袱讹、stack 棧 模板

4.1 stack 棧的初始化


#include <iostream>
#include <stack>

using namespace std;

void main()
{
    stack<int> s;
    for (int i = 0; i < 10; i++)
    {
        s.push(i + 1);
    }

    while (!s.empty())
    {
        int tmp = s.top();
        cout << tmp << endl;
        s.pop();
    }

    system("pause");
}

5、list 模板

5.1 list 初始化


#include <iostream>
#include <list>

using namespace std;

void printList(list<int>& lst)
{
    //迭代器
    //沒有重載“<”運(yùn)算符
    for (list<int>::iterator it = lst.begin(); it != lst.end(); it++)
    {
        cout << *it << endl;
    }
}
//基本操作
/*
void main()
{
    list<int> lst;
    for (int i = 0; i < 10; i++)
    {
        //尾部插入元素
        lst.push_back(i);
    }

    //頭部插入元素
    lst.push_front(80);
    lst.push_front(90);

    list<int>::iterator it = lst.begin();
    it++;
    cout << *it << endl;
    //it = it + 3; 注意:不支持隨機(jī)訪問       

    printList(lst);

    system("pause");
}

5.2 list 插入


#include <iostream>
#include <list>

using namespace std;

void main()
{
    list<int> lst;
    for (int i = 0; i < 10; i++)
    {
        //尾部插入元素
        lst.push_back(i);
    }

    list<int>::iterator it = lst.begin();
    it++;
    lst.insert(it, 100);

    printList(lst);
    system("pause");
}

5.3 list 初始化


#include <iostream>
#include <list>

using namespace std;

void main()
{
    list<int> lst;
    for (int i = 0; i < 10; i++)
    {
        //尾部插入元素
        lst.push_back(i);
    }

    list<int>::iterator it = lst.begin();
    //刪除
    it++;
    //刪除第二個元素
    //lst.erase(it);

    //刪除區(qū)間(已經(jīng)被刪除了元素不能再刪除)
    list<int>::iterator it_begin = lst.begin();
    list<int>::iterator it_end = lst.begin();
    it_end++;
    it_end++;
    it_end++;
    lst.erase(it_begin, it_end);

    //直接根據(jù)內(nèi)容刪除元素
    lst.remove(5);

    printList(lst);

    system("pause");
}

6昵时、set 模板

6.1 set 初始化

#include <iostream>
#include <set>

using namespace std;

//set 元素唯一 默認(rèn)從小到大
void printSet(set<int> &s)
{
    for (set<int>::iterator it = s.begin(); it != s.end(); it++)
    {
        cout << *it << endl;
    }
}

void main()
{
    set<int> s;
    //添加元素
    for (int i = 0; i < 10; i++)
    {
        s.insert(i+1);
    }
    s.insert(20);
    s.insert(15);
    s.insert(15);

    //刪除
    set<int>::iterator it = s.begin();
    it++;
    s.erase(it);    

    printSet(s);
    system("pause");
}

6.2 set 元素按照從大到小排列

#include <iostream>
#include <set>
#include <functional>
using namespace std;

void main()
{
    //同Java中:Map<String,List<String>> 
    set<int,greater<int>> s;
    s.insert(10);
    s.insert(5);
    s.insert(20);
    s.insert(99);

    for (set<int,greater<int>>::iterator it = s.begin(); it != s.end(); it++)
    {
        cout << *it << endl;
    }

    system("pause");
}

6.3 set 自定義排序規(guī)則

#include <iostream>
#include <set>
#include <functional>
using namespace std;

//元素類型為Teacher對象捷雕,按照年齡排序

class Teacher
{
public:
    Teacher(char* name, int age)
    {
        this->name = name;
        this->age = age;
    }

    void print()
    {
        cout << name << "," << age << endl;
    }

public:
    char* name;
    int age;
};

//自定義排序規(guī)則
//仿函數(shù)
struct MyAgeSorter
{
    bool operator()(const Teacher &left, const Teacher &right)
    {
        return left.age < right.age;
    }
};

void main()
{
    set<Teacher, MyAgeSorter> s;
    s.insert(Teacher(const_cast<char*>("jack"),18));
    s.insert(Teacher(const_cast<char*>("rose"), 20));
    s.insert(Teacher(const_cast<char*>("jason"), 22));
    s.insert(Teacher(const_cast<char*>("alan"), 5));
    //s.insert(Teacher("jimy", 5)); //不會插入

    for (set<Teacher>::iterator it = s.begin(); it != s.end(); it++)
    {
        cout << (*it).name << "," << (*it).age << endl;
    }

    system("pause");
}

6.3 set 查找

#include <iostream>
#include <set>
using namespace std;

void main()
{
    set<int> s;
    //添加元素
    for (int i = 0; i < 10; i++)
    {
        s.insert(i + 1);
    }

    //printSet(s);

    //等于4的元素指針
    set<int>::iterator s_4 = s.lower_bound(4); 
    //cout << *s_4 << endl;
    //大于4的元素指針
    set<int>::iterator s_5 = s.upper_bound(4);
    //cout << *s_5 << endl;

    //一次性獲取等于4的元素指針椒丧,和大于4的元素指針\
    //BasicNameValuePair
    pair<set<int>::iterator, set<int>::iterator> p = s.equal_range(4);
    cout << *p.first << endl;
    cout << *p.second << endl;
    system("pause");
}

6.4 multiset 允許重復(fù)的元素

#include <iostream>
#include <set>
using namespace std;
void main()
{
    multiset<int> s;
    s.insert(2);
    s.insert(8);
    s.insert(2);
    s.insert(8);

    for (multiset<int>::iterator it = s.begin(); it != s.end(); it++)
    {
        cout <<  *it << endl;
    }

    system("pause");
}

7、map 模板

7.1 map 初始化

#include <iostream>
#include <map>
#include <string>
using namespace std;

void main()
{
    //key -> value
    //1.
    map<int, string> map1;
    map1.insert(pair<int, string>(1, "jack"));
    map1.insert(pair<int, string>(2, "rose"));

    //2
    map1.insert(make_pair(3, "jason"));

    //3
    map1.insert(map<int, string>::value_type(4, "alan"));

    //4
    map1[5] = "jimmy"; //map["NO1"] = 90;

    //前三種方式非区,如果key已經(jīng)存在瓜挽,重復(fù)添加會報錯
    //第四種方式,如果key已經(jīng)存在征绸,重復(fù)添加會覆蓋

    //遍歷輸出
    for (map<int, string>::iterator it = map1.begin(); it != map1.end(); it++)
    {
        cout << it->first << "," << it->second << endl;
    }


    system("pause");
}

7.2 map 刪除元素的方式

#include <iostream>
#include <map>
#include <string>
using namespace std;

void printMap(map<int, string> &map1)
{
    for (map<int, string>::iterator it = map1.begin(); it != map1.end(); it++)
    {
        cout << it->first << "," << it->second << endl;
    }
}

void main()
{
    map<int, string> map1;
    map1.insert(pair<int, string>(1, "jack"));
    map1.insert(pair<int, string>(2, "rose"));
    map1.insert(pair<int, string>(3, "jason")); 

    map<int, string>::iterator it = map1.begin();
    it++;
    map1.erase(it);

    printMap(map1);

    system("pause");
}

7.3 map 添加元素的結(jié)果

#include <iostream>
#include <map>
#include <string>
using namespace std;

void main()
{
    map<int, string> map1;
    map1.insert(pair<int, string>(1, "jack"));
    map1.insert(pair<int, string>(2, "rose"));
    map1.insert(pair<int, string>(3, "jason"));
    //獲取添加的結(jié)果(first元素指針久橙,second 是否成功)
    pair<map<int, string>::iterator, bool> res = map1.insert(pair<int, string>(3, "alan"));
    if (res.second)
    {
        cout << "添加成功" << endl;
    }
    else
    {
        cout << "添加失敗" << endl;
    }

    printMap(map1);

    system("pause");
}

7.3 map 查找

#include <iostream>
#include <map>
#include <string>
using namespace std;

void main()
{
    map<int, string> map1;
    map1.insert(pair<int, string>(1, "jack"));
    map1.insert(pair<int, string>(2, "rose"));
    map1.insert(pair<int, string>(3, "jason")); 

    printMap(map1);

    cout << "---------" << endl;

    //獲取key等于大于5的元素的值
    pair<map<int, string>::iterator, map<int, string>::iterator> p = map1.equal_range(2);
    if (p.first != map1.end()){
        //等于2的元素key value
        cout << p.first->first << p.first->second << endl;

        //大于2的元素key value
        cout << p.second->first << p.second->second << endl;
    }

    system("pause");
}

7.3 multimap

#include <iostream>
#include <map>
#include <string>
using namespace std;

//一個key對應(yīng)多個value
//一個部門多個員工
//multimap

class Employee
{
public:
    Employee(char* name,int age)
    {
        this->name = name;
        this->age = age;
    }

public:
    char* name;
    int age;
};

void main()
{
    multimap<string, Employee> map1;

    //開發(fā)部
    map1.insert(make_pair("開發(fā)", Employee(const_cast<char*>("擱淺"), 20)));
    map1.insert(make_pair("開發(fā)", Employee(const_cast<char*>("彪哥"), 20)));

    //財務(wù)
    map1.insert(make_pair("財務(wù)", Employee(const_cast<char*>("小穎"), 16)));
    map1.insert(make_pair("財務(wù)", Employee(const_cast<char*>("rose"), 20)));

    //銷售
    map1.insert(make_pair("銷售", Employee(const_cast<char*>("阿呆"), 30)));
    map1.insert(make_pair("銷售", Employee(const_cast<char*>("呵呵"), 30)));

    //遍歷輸出
    for (multimap<string, Employee>::iterator it = map1.begin(); it != map1.end(); it++)
    {
        cout << it->first << "," << it->second.name  << "," << it->second.age << endl;
    }

    cout << "----------------" << endl;
    //只獲取“財務(wù)”部的員工
    //獲取“財務(wù)部”員工的個數(shù),key對應(yīng)的value的個數(shù)
    int num = map1.count("財務(wù)");
    multimap<string, Employee>::iterator it = map1.find("財務(wù)");
    int c = 0; //控制循環(huán)的次數(shù)
    while (it != map1.end() && c < num)
    {
        cout << it->first << "," << it->second.name << "," << it->second.age << endl;
        it++;
        c++;
    }

    system("pause");
}

8管怠、深拷貝與淺拷貝

#include <iostream>
#include <map>
#include <string>
#include <vector>

using namespace std;

class Employee
{
public:
    //構(gòu)造函數(shù)
    Employee(char* name, int age)
    {
        this->name = new char[strlen(name) + 1];
        strcpy(this->name, name);
        this->age = age;
    }

    //析構(gòu)函數(shù)
    ~Employee()
    {
        if (this->name != NULL)
        {
            delete[] this->name;
            this->name = NULL;
            this->age = 0;
        }
    }
    //拷貝構(gòu)造函數(shù)
    //Employee e = 
    Employee(const Employee &obj)
    {
        this->name = new char[strlen(obj.name) + 1];
        strcpy(this->name, obj.name);
        this->age = obj.age;
    }

    //重載=
    //e1 = e2;
    Employee& operator=(const Employee &obj)
    {
        //釋放舊的內(nèi)存
        if (this->name != NULL)
        {
            delete[] this->name;
            this->name = NULL;
            this->age = 0;
        }

        //重新分配
        this->name = new char[strlen(obj.name) + 1];
        strcpy(this->name, obj.name);
        this->age = obj.age;

        return *this;
    }

public:
    char* name;
    int age;
};

void func()
{
    vector<Employee> v1;
    Employee e1(const_cast<char*>("jack"), 20);
    v1.push_back(e1);
}

void main()
{
    //vector<Employee> v1;
    //Employee e1("jack",20);
    //將e1拷貝到vector中
    //v1.push_back(e1);

    func();

    system("pause");
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末淆衷,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子渤弛,更是在濱河造成了極大的恐慌祝拯,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件她肯,死亡現(xiàn)場離奇詭異佳头,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)晴氨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進(jìn)店門康嘉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人籽前,你說我怎么就攤上這事亭珍。” “怎么了枝哄?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵肄梨,是天一觀的道長。 經(jīng)常有香客問我挠锥,道長众羡,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任蓖租,我火速辦了婚禮纱控,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘菜秦。我一直安慰自己,他們只是感情好舶掖,可當(dāng)我...
    茶點故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布球昨。 她就那樣靜靜地躺著,像睡著了一般眨攘。 火紅的嫁衣襯著肌膚如雪主慰。 梳的紋絲不亂的頭發(fā)上嚣州,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天,我揣著相機(jī)與錄音共螺,去河邊找鬼该肴。 笑死,一個胖子當(dāng)著我的面吹牛藐不,可吹牛的內(nèi)容都是我干的匀哄。 我是一名探鬼主播,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼雏蛮,長吁一口氣:“原來是場噩夢啊……” “哼涎嚼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起挑秉,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤法梯,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后犀概,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體立哑,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年姻灶,在試婚紗的時候發(fā)現(xiàn)自己被綠了铛绰。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡木蹬,死狀恐怖至耻,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情镊叁,我是刑警寧澤尘颓,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站晦譬,受9級特大地震影響疤苹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜敛腌,卻給世界環(huán)境...
    茶點故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一卧土、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧像樊,春花似錦尤莺、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春友酱,著一層夾襖步出監(jiān)牢的瞬間晴音,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工缔杉, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留锤躁,地道東北人。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓或详,卻偏偏與公主長得像系羞,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子鸭叙,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容