新しいセットを作成し、カスタム ソート関数を使用してカスタム ソート関数を作成することにより、STL セットを再分類しようとしています。その方法については、以前の qn を参照してください。
これは、 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 では正常にコンパイルされます
エラー C2440: '初期化中': 'std::_Tree_const_iterator<_Mytree>' から 'std::_Tree_const_iterator<_Mytree>' に変換できません
エラー C2678: バイナリ '!=' : 型 'std::_Tree_const_iterator<_Mytree>' の左側のオペランドを取る演算子が見つかりません (または、受け入れ可能な変換がありません)
system_error(425): '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) このサンプル コードが Qunicy2005 では機能するのに、MS Studio 2010 では機能しない理由を理解する
2) MS Studio 2010 でも動作するコードのサンプルを取得するにはどうすればよいですか?