这些日子,因为工作需要,需要在界面上画三条线,每条线上绘制若干个十字,每条线上的十字个数不一定相同,能方便的根据坐标添加、删除、修改、查找十字点。
定义类如下:
class CbdShiZhi
{
public:
CbdShiZhi();
virtual ~CbdShiZhi();
CbdShiZhi(int x1,int y1,int c1,float gx1,float gy1,int l1);
int getx();
void setx(int x_temp);
int gety();
void sety(int y_temp);
int getcolor();
void SetColor(int color_temp);
float GetGlobalx();
float GetGlobaly();
void SetGlobalx(float globalx_temp);
void SetGlobaly(float globaly_temp);
int GetLine();
void SetLine(int line_temp);
int x;//十字点x坐标
int y;//十字点y坐标
int ShiZhi_color;//十字点颜色
float global_x;//该点对应的世界坐标x
float global_y; //该点对应的世界坐标y
int ShiZhi_line;//结构体直线
};
用STL存储自定义类对象,每增加一个十字便实例化一个对象,添加到vector中。在vc 6.0中使用vector需要
#include <vector>
#include<algorithm>
using namespace std;
必须包含命名空间,否则会提示错误。
十字vector定义如下:
vector<CbdShiZhi> shizhivector;
三条直线可以定义一个vector数组vector<CbdShiZhi> shizhivector[3];
为了说明方便,以一条直线为例。
在程序中,需要对vector中元素进行排序,vector默认的排序方式为升序,必须重载<运算符。将下边函数添加到类的定义中。
bool operator<(const CbdShiZhi & temp2) const
{
return x<=temp2.x;
}
排序时,调用sort函数:
sort(shizhivector.begin(),shizhivector.end());
还有其它方法可以实现升序排序:
1)自定义比较函数
bool cmp(const CbdShiZhi &temp1,const CbdShiZhi &temp2)
{
return temp1.x>temp2.x;
}
调用sort函数如下:
sort(shizhivector.begin(),shizhivector.end(),cmp);
2)在类中重载()运算符
bool operator()(const CbdShiZhi temp11,const CbdShiZhi temp12)
{
return temp11.x>temp12.x; //变量可以自己设定,根据那个成员排序,可以自己设定
}
注意:类中成员变量必须为public类型,否则会提示错误如下:
c:/program files/microsoft visual studio/vc98/include/algorithm(583) : error C2248: '<' : cannot access private member declared in class 'CbdShiZhi'
e:/修改程序/gptransfer/gptransfer/bdshizhi.h(42) : see declaration of '<'
c:/program files/microsoft visual studio/vc98/include/algorithm(548) : see reference to function template instantiation 'void __cdecl std::_Unguarded_insert(class CbdShiZhi *,class CbdShiZhi)' being compiled
并且:必须直接使用成员变量,不可以间接通过成员函数调用成员变量。
如果将程序修改如下:
bool operator()(const CbdShiZhi temp11,const CbdShiZhi temp12)
{
return temp11.getx()>temp12.getx(); //变量可以自己设定,根据那个成员排序,可以自己设定
}