天天看點

C++學習之STL容器vector

學習知識點

vector容器的添加、删除,周遊操作。

練習代碼

// IPCT.cpp : 定義控制台應用程式的入口點。
//

#include "stdafx.h"
#include <vector>
#include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
using namespace std;

BOOL find(char *ip);
class MoveHotel
{
public:
char ip[16];
char mac[18];
char mark[100];
    MoveHotel(char _ip[],char _mac[],char _mark[])
    {
//ip=_ip;
//mac=_mac;
//mark=_mark;
        strcpy(ip,_ip);
        strcpy(mac,_mac);
        strcpy(mark,_mark);
    }
};
vector<MoveHotel *> hostlist;
int _tmain(int argc, _TCHAR* argv[])
{

    FILE *fp;
    fp=fopen("d:\\mac.txt","r");
if (!fp)
    {
return 0;
    }
while(!feof(fp))
        {
char ip[16],mac[18],info[100];
            fscanf(fp,"IP:%s\tMAC:%s\t備注:%s\n",ip,mac,info);
            printf("正在插入——%s\n",ip);
            hostlist.push_back(new MoveHotel(ip,mac,info));
        }
    printf("完成!\n");
    fclose(fp);

while (1)
    {
char read[20];
        scanf("%s",&read);
if(StrCmp(read,"exit")==0)
        {
break;
        }
else
        {
if (find(read))
            {
                printf("查找完成!\n");
            }
else
            {
                printf("沒有%s相關的内容!\n",read);
            }
        }
    }

    vector<MoveHotel *>::iterator i;
for (i=hostlist.begin();i!=hostlist.end();i++)
    {
        printf("%s%s%s\n",(*i)->ip,(*i)->mac,(*i)->mark);
    }
//vector<Sprite *>::iterator i;    //訓示器i:數組指針,儲存元素位址的位址代号
            for (i=hostlist.begin();i!=hostlist.end();i++)    //注意為:i!=m_vSprites.end()因為是儲存着位址序列;而非整數序列
            {
                delete *i;
            }
        hostlist.clear();
//vector<MoveHotel *>(hostlist).swap(MoveHotel);    //建立新容器并無空複制原容器資料,再交換兩個容器内的資料;達到壓縮的目的;相當于ArrayList中的TrimToSize()
    return 0;
}

BOOL find(char *ip)
{
if (!hostlist.empty())
    {
        vector<MoveHotel *>::iterator i;
for (i=hostlist.begin();i!=hostlist.end();i++)
        {
if (StrCmp((*i)->ip,ip)==0)
            {
                printf("IP:%s\nMAC:%s\nMARK:%s\n",(*i)->ip,(*i)->mac,(*i)->mark);
return TRUE;
            }

        }
    }
return FALSE;
}