我正在尝试通过创建一个新集并使用自定义排序函数创建一个自定义排序函数来使用 STL 集,please refer to my previous qn on how its done
这是代码示例的简化版本,可在 Quincy 2005(G++ 编译器)中运行,但在 Microsoft Studios 2010 中不起作用
#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; ;
}
在 MS Studio 2010 中编译时出现以下错误,在 Quincy 2005 中编译正常
error C2440: 'initializing' : cannot convert from 'std::_Tree_const_iterator<_Mytree>' to 'std::_Tree_const_iterator<_Mytree>'
Error C2678: binary '!=' : no operator found which takes a left-hand operand of type 'std::_Tree_const_iterator<_Mytree>' (or there is no acceptable conversion
system_error(425): could be 'bool std::operator !=(const std::error_code &,const std::error_condition &)'
我确信它与自定义排序函数有关,因为当我尝试使用 SortByYX 作为我的比较函数创建一个新集合时出现问题
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;
}
};
我需要帮助
1) 了解为什么此代码示例在 Quicy2005 中有效但在 MS Studio 2010 中无效
2) 我如何获得在 MS Studio 2010 中工作的代码示例
最佳答案
你这里的迭代器类型错误:
set<Point2D>::iterator p22 = p2d_set2.begin();
你需要
set<Point2D, SortByYX>::iterator p22 = p2d_set2.begin();
记住,set<Point2D>
和 set<Point2D, SortByYX>
是不同的类型,所以他们也是 iterator
关于c++ - STL 设置自定义排序功能在 Quicy 2005 中有效,但在 MS Studio 2010 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19982806/