首页 > 代码库 > 一个关于STL list使用 小示例

一个关于STL list使用 小示例

#include <list>
#include <string>
using namespace std;
typedef struct DiskInfo_st
{
    int diskNo;
    bool isUsed;
    string diskName;
} DiskInfo;

class DiskManager
{
private:
    list<DiskInfo> m_list;

public:
    bool AddDisk(const string& name);
    bool RemoveDisk(int num);
    void Traverse();
};

 

#include "disk_manager.h"

bool DiskManager::AddDisk(const string& name)
{

    for(list<DiskInfo>::iterator it = m_list.begin(); it != m_list.end(); it++)
    {
        if(!(*it).isUsed)
        {
            (*it).diskName = name;
            (*it).isUsed = true;
            return true;
        }
    }
    DiskInfo disk;
    disk.diskNo = m_list.size();
    disk.diskName = name;
    disk.isUsed = true;
        
    cout << "hello" << endl;
    m_list.push_back(disk);
    return true;
}

bool DiskManager::RemoveDisk(int num)
{
    if(num < 0 || num >= m_list.size())
    {
        cout << "The No. of disk is wrong." << endl;
        return false; 
    }
    for(list<DiskInfo>::iterator it = m_list.begin(); it != m_list.end(); it++)
    {
        if((*it).diskNo == num)
        {
            (*it).isUsed = false;
            return true;
        }
    }
}

void DiskManager::Traverse()
{
    for(list<DiskInfo>::iterator it = m_list.begin(); it != m_list.end(); it++)
    {
        cout << "No. " << (*it).diskNo;
        cout << " name: " << (*it).diskName;
        cout << " usedState: " << ((*it).isUsed ? "Yes" : "No") << endl;
    }
}

 

#include <iostream>
#include "disk_manager.h"

using namespace std;

int main(int argc, char *argv[])
{
    DiskManager diskManager;
    diskManager.AddDisk("sda");
    diskManager.AddDisk("sdb");
    diskManager.AddDisk("sdc");
    diskManager.AddDisk("sdd");
    diskManager.AddDisk("sdf");
    diskManager.Traverse();
    cout << endl << endl;
    diskManager.RemoveDisk(1);
    diskManager.Traverse();
    cout << endl << endl;
    diskManager.AddDisk("sdg");
    diskManager.Traverse();
    
    cout << endl << endl;
    diskManager.AddDisk("sdj");
    diskManager.Traverse();
    return 0;
}

 

技术分享

 

一个关于STL list使用 小示例