ラムダ式での比較演算子

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
Sx1752
記事: 3
登録日時: 13年前

ラムダ式での比較演算子

#1

投稿記事 by Sx1752 » 13年前

コード:

#include <cstring>
class Item
{
private:
	int id;
	char name[32];

public:
	Item(const int id = 0, const char *name = nullptr)
	{
		this->id = id;
		
		if(!name)
			::strcpy(this->name, "");
		else
			::strcpy(this->name, name);
	}
	
	const int getId() const
	{
		return id;
	}
	
	const char* getName() const
	{
		return name;
	}
	
	bool operator<(const Item another) const
	{
		return this->id < another.id;
	}
	
	bool operator>(const Item another) const
	{
		return this->id > another.id;
	}
};

#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;
typedef vector<Item> ItemVector;

int main(int argc, char **argv)
{
	ItemVector itemVector;
	
	itemVector.push_back(Item(2, "アイテム2"));
	itemVector.push_back(Item(4, "アイテム4"));
	itemVector.push_back(Item(1, "アイテム1"));
	itemVector.push_back(Item(3, "アイテム3"));
	itemVector.push_back(Item(0, "アイテム0"));
	
	stable_sort(itemVector.begin(), itemVector.end(), [](const Item& a, const Item& b) { return a < b; } );
	
	for(ItemVector::iterator iter = itemVector.begin();
		iter != itemVector.end();
		++iter) {
		printf("%d: %s\n", iter->getId(), iter->getName());
	}
	
	return 0;
}
アイテムクラスを作ってstable_sortしたいのですが、
コンパイル時に比較演算子をconstメンバにしないとコンパイルできないのは何故なのでしょうか。

beatle
記事: 1281
登録日時: 14年前
住所: 埼玉
連絡を取る:

Re: ラムダ式での比較演算子

#2

投稿記事 by beatle » 13年前

お示しのコードはコンパイルに失敗するコードですか?それとも成功するコード?
試しにIdeoneでコンパイルしてみたら、成功しました。
http://ideone.com/xzvz0G

アバター
みけCAT
記事: 6734
登録日時: 15年前
住所: 千葉県
連絡を取る:

Re: ラムダ式での比較演算子

#3

投稿記事 by みけCAT » 13年前

コード:

[](const Item& a, const Item& b) { return a < b; }
ここの引数の宣言がconstだからじゃないでしょうか?
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

Sx1752
記事: 3
登録日時: 13年前

Re: ラムダ式での比較演算子

#4

投稿記事 by Sx1752 » 13年前

beatle さんが書きました:お示しのコードはコンパイルに失敗するコードですか?それとも成功するコード?
ここに貼ったのは成功するコードです。
みけCAT さんが書きました:

コード:

[](const Item& a, const Item& b) { return a < b; }
ここの引数の宣言がconstだからじゃないでしょうか?
どうやらそのようですね。ラムダ式の

コード:

[](Item& a, Item& b) { return a < b; }

コード:

[](Item a, Item b) { return a < b; }
に変更するとコンパイルできました。
しかし、a, bを参照型にするとやっぱりコンパイル出来ないです。
► スポイラーを表示

アバター
h2so5
副管理人
記事: 2212
登録日時: 15年前
住所: 東京
連絡を取る:

Re: ラムダ式での比較演算子

#5

投稿記事 by h2so5 » 13年前

ソート中に a, b を変更してはいけないので、コンパイルできないのは仕様です。

Sx1752
記事: 3
登録日時: 13年前

Re: ラムダ式での比較演算子

#6

投稿記事 by Sx1752 » 13年前

h2so5 さんが書きました:ソート中に a, b を変更してはいけないので、コンパイルできないのは仕様です。
仕様でしたか。お答えいただきありがとうございました。

閉鎖

“C言語何でも質問掲示板” へ戻る