C++ STL设置自定义排序功能在Qunicy 2005中有效,但在MS Studio 2010中无效
我试图通过创建一个新集合并创建一个带有自定义排序函数的自定义排序函数来使用STL集合 这是一个简化版的代码示例,在Quincy2005(G++编译器)中可用,但在Microsoft Studio 2010中不可用C++ STL设置自定义排序功能在Qunicy 2005中有效,但在MS Studio 2010中无效,c++,visual-studio-2010,debugging,stl,set,C++,Visual Studio 2010,Debugging,Stl,Set,我试图通过创建一个新集合并创建一个带有自定义排序函数的自定义排序函数来使用STL集合 这是一个简化版的代码示例,在Quincy2005(G++编译器)中可用,但在Microsoft Studio 2010中不可用 #include <iostream> #include <string> #include <fstream> #include <set> #include <cmath> using namespace std;
#include <iostream>
#include <string>
#include <fstream>
#include <set>
#include <cmath>
using namespace std;
class Point2D
{
public:
int getX() const;
int getY() const;
void setX(int);
void setY(int);
bool operator < ( const Point2D& x2) const
{
if ( x != x2.x)
{
return x < x2.x;
}
if ( y != x2.y)
{
return y < x2.y;
}
};
protected:
int x;
int y;
};
struct SortByYX
{
bool operator ()(const Point2D& ptd1, const Point2D& ptd2) const
{
if ( ptd1.getY() != ptd2.getY())
{
return ptd1.getY() < ptd2.getY();
}
if ( ptd1.getX() != ptd2.getX() )
{
return ptd1.getX() < ptd2.getX();
}
return false;
}
};
int main()
{
set<Point2D> p2d_set;
Point2D p2d;
p2d.setX(1);
p2d.setY(3);
p2d_set.insert(p2d);
p2d.setX(3);
p2d.setY(2);
p2d_set.insert(p2d);
set<Point2D>::iterator p2 = p2d_set.begin();
while ( p2 != p2d_set.end() )
{
cout<<p2->getX()
<<" "
<<p2->getY()
<<endl;
p2++;
}
set<Point2D, SortByYX> p2d_set2(p2d_set.begin(), p2d_set.end());
set<Point2D>::iterator p22 = p2d_set2.begin();
cout<<endl
<<endl;
while ( p22 != p2d_set2.end() )
{
cout<<p22->getX()
<<" "
<<p22->getY()
<<endl;
p22++;
}
}
int Point2D::getX() const
{
return x;
}
int Point2D::getY() const
{
return y;
}
void Point2D::setX(int x1)
{
x = x1;
}
void Point2D::setY(int y1)
{
y = y1; ;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
类Point2D
{
公众:
int getX()常量;
int getY()常量;
void setX(int);
void setY(int);
布尔运算符<(常数点2D和x2)常数
{
如果(x!=x2.x)
{
返回x 这里的迭代器类型是否错误:
set<Point2D>::iterator p22 = p2d_set2.begin();
set::迭代器p22=p2d_set2.begin();
你需要
set<Point2D, SortByYX>::iterator p22 = p2d_set2.begin();
set::迭代器p22=p2d_set2.begin();
请记住,set
和set
是不同的类型,它们的iterator
s也是不同的类型。我为什么不必声明set::iterator p22=p2d_set2.begin();它在昆西2005中起作用???@Computernerd是昆西2005的一个特性(实际上是bug)。根据定义,它们是不同的类型。
set<Point2D, SortByYX>::iterator p22 = p2d_set2.begin();