• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

异度空间

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

CList的一个使用例子

CArray内部是用了单线数组,而CList内部则用了双向链表,当数据量大的时候,效率是截然不同的。

下面是一个简单的CList使用例子,VC Win32 console工程。

// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "test.h"
#include <afxtempl.h>
#include <iostream>
using namespace std;

class Point
{

public:
    Point()
    {
        m_x = 0;
        m_y = 0;
    }

    Point(int x, int y)
    {
        m_x = x;
        m_y = y;
    }

bool operator==(const Point& src) const
    {
        return ( (m_x == src.m_x) && (m_y == src.m_y) );
    }

public:
    int m_x;
    int m_y;
};

typedef CList<Point, Point&>           CPntLst;

int main()

{  
    CPntLst     lst;
    Point       point, elem1, elem2;
    elem1.m_x = 52;
    elem1.m_y = 102;
    elem2.m_x = 14;
    elem2.m_y = 1621;


    // add a element from tail, certainly, also can from head
    lst.AddTail(elem1);
    lst.AddTail(elem2);

// print the point count
cout<< "count: "<<lst.GetCount()<<endl;

// traverse the whole list
cout << "First time:"n";
size_t index = 0;

POSITION ps;

for( /*POSITION*/ ps = lst.GetHeadPosition();ps;lst.GetNext(ps) )  

{         
   // extract the point according the current position  
   point = lst.GetAt(ps);  
   printf("index: %d, m_x = %d, m_y = %d"n", index++, point.m_x, point.m_y);  
}

// search the point which is equal to elem1
ps = lst.Find(elem1);
point = lst.GetAt(ps);

printf("elem1: m_x = %d, m_y = %d"n", point.m_x, point.m_y);

Point elem3(123, 123123);

// insert elem3 into the list after elem1
lst.InsertAfter(ps, elem3);
cout << "Second time:"n";
for( ps = lst.GetHeadPosition();ps;lst.GetNext(ps) )  
{         
   // extract the point according the current position  
   point = lst.GetAt(ps);  
   printf("index: %d, m_x = %d, m_y = %d"n", index++, point.m_x, point.m_y);  
}

// remove elem1
ps = lst.Find(elem1);
lst.RemoveAt(ps);
cout << "Third time:"n";
for( ps = lst.GetHeadPosition();ps;lst.GetNext(ps) )  
{         
   // extract the point according the current position  
   point = lst.GetAt(ps);  
   printf("index: %d, m_x = %d, m_y = %d"n", index++, point.m_x, point.m_y);  
}

// remove all the rest
lst.RemoveAll();
cout << "Fourth time:"n";
for( ps = lst.GetHeadPosition();ps;lst.GetNext(ps) )  
{         
   // extract the point according the current position  
   point = lst.GetAt(ps);  
   printf("index: %d, m_x = %d, m_y = %d"n", index++, point.m_x, point.m_y);  
}

return 0;

}

posted on 2008-12-29 13:30  madlas  阅读(1616)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3