- PR -

C++(マネージ) IComparerについて

1
投稿者投稿内容
ken
大ベテラン
会議室デビュー日: 2006/03/29
投稿数: 121
お住まい・勤務地: 東京
投稿日時: 2006-07-19 14:20
OS:XP
VisualStudio2005 C++

ソート処理をカスタマイズして実装させたいと
考えているのですが、(C#では、出来ました)
C++(マネージ)版では、どのように記述すれば良いのでしょうか?
よろしく御願いいたします。

C++−−−−−−−−−−−−−−−−−−−−−
XX.h

namespace test
{
//省略
}
public ref class comp : System::Collections::IComparer
{
//public: int Compare(object x, object y);
}
−−−−−−−−−−−−−−−−−−−−−−−

C#−−−−−−−−−−−−−−−−−−−−−−
public class StrLenComparer : IComparer
{
public int Compare(object x, object y)
{
* 省略
}
}
−−−−−−−−−−−−−−−−−−−−−−−
Kazuki
ぬし
会議室デビュー日: 2004/10/13
投稿数: 298
投稿日時: 2006-07-19 22:33
コード:
public ref class comp : public System::Collections::IComparer // <- publicがいるんじゃないですか?
{
public:
    int Compare(Object^ x, Object^ y) // <- 引数の型はObject^じゃないかな
    {
        // 後はご自由に
    }
 	//public: int Compare(object x, object y);
}; // <-セミコロンいるんじゃないかな



参考になるかわかりませんが,簡単な実装例(キャストとかめんどくさかったので
Generic版ですが参考になると思います)

コード:
// ICompareTest.cpp : メイン プロジェクト ファイルです。

#include "stdafx.h"

using namespace System;
using namespace System::Collections::Generic;

public ref class Person
{
public:
	Person(String^ name)
	{
		Name = name;
	}
	property String^ Name;
};

public ref class Comp : public IComparer<Person^>
{
public:
	virtual int Compare(Person^ x, Person^ y)
	{
		if(x == y)
		{
			return 0;
		}
		if(x == nullptr)
		{
			return -1;
		}
		if(y == nullptr)
		{
			return 1;
		}
		return x->Name->CompareTo(y->Name);
	}
};

void Print(IEnumerable<Person^>^ e)
{
	for each(Person^ p in e)
	{
		Console::WriteLine(p->Name);
	}
}

int main(array<System::String ^> ^args)
{
    List<Person^>^ ps = gcnew List<Person^>();
	ps->Add(gcnew Person(L"Maro"));
	ps->Add(gcnew Person(L"Aaro"));
	ps->Add(gcnew Person(L"Faro"));
	Console::WriteLine(L"ソート前");
	Print(ps);

	ps->Sort(gcnew Comp());
	Console::WriteLine(L"ソート後");
	Print(ps);
    return 0;
}

ken
大ベテラン
会議室デビュー日: 2006/03/29
投稿数: 121
お住まい・勤務地: 東京
投稿日時: 2006-07-21 09:54
Kazuki様
レスありがとうございます。

解決いたしました。
ありがとうございました。
1

スキルアップ/キャリアアップ(JOB@IT)