5

std ::map-containerのキーとしてstd::tm()を使用したいと思います。しかし、コンパイルしようとすると、多くの(10)エラーが発生します。

例えば:

1.1。

エラーC2784:'bool std :: operator <(const std :: basic_string <_Elem、_Traits、_Alloc>&、const _Elem *)':'const std :: basic_string <_Elem、_Traits、_Alloc>のテンプレート引数を推測できませんでした&'from' const tm'c:\ program files(x86)\ microsoft visual studio 10.0 \ vc \ include \ xfunctional 125

2.2。

エラーC2784:'bool std :: operator <(const _Elem *、const std :: basic_string <_Elem、_Traits、_Alloc>&)':'const_Elem*'のテンプレート引数を'consttm' c:\から推測できませんでしたプログラムファイル(x86)\ microsoft visual studio 10.0 \ vc \ include \ xfunctional 125

3.3。

エラーC2784:'bool std :: operator <(const std :: vector <_Ty、_Ax>&、const std :: vector <_Ty、_Ax>&)':'const std ::vector<のテンプレート引数を推測できませんでした_Ty、_Ax>&'from' const tm'c:\ program files(x86)\ microsoft visual studio 10.0 \ vc \ include \ xfunctional 125

これはすべて、2つのstd :: tmを比較する関数オブジェクトを「単に」作成する必要があることを意味します。これには標準比較が定義されていないためですか?それとも別のトリックがありますか?(または私には不可能かもしれませんか?^^)

コード:

#include <map>
#include <ctime>
#include <string>


int main()
{
    std::map<std::tm, std::string> mapItem;
    std::tm TM;

    mapItem[TM] = std::string("test");
    return 0;
};
4

4 に答える 4

8

std::map比較子を使用して、キーが既に存在するかどうかを確認します。したがって、を使用する場合はstd::tm、3 番目の引数として比較子も指定する必要があります。

template < class Key, class T, class Compare = less<Key>,
           class Allocator = allocator<pair<const Key,T> > > class map

したがって、解決策はファンクターになります(すでに推測したとおり):

struct tm_comparer
{
   bool operator () (const std::tm & t1, const std::tm & t2) const
   {           //^^ note this

        //compare t1 and t2, and return true/false
   }
};

std::map<std::tm, std::string, tm_comparer> mapItem;
                             //^^^^^^^^^^ pass the comparer!

または自由関数 ( operator <) を次のように定義します。

bool operator < (const std::tm & t1, const std::tm & t2)
{          // ^ note this. Now its less than operator

    //compare t1 and t2, and return true/false
};

std::map<std::tm, std::string> mapItem; //no need to pass any argument now!
于 2011-05-12T14:03:09.380 に答える
2

はい、演算子std::tmを定義しません。<

于 2011-05-12T14:01:54.363 に答える
2

フリー関数で十分です。関数オブジェクトは必要ありません。

于 2011-05-12T14:02:53.957 に答える
2

はい、tm 構造体に operator< を定義する必要があります。たとえば、http://www.cplusplus.com/reference/stl/map/map/を参照してください (ページの下部)。

于 2011-05-12T14:03:23.140 に答える