ユースケース:レコードのバッファ。ここに基本的な考え方があります。 レコード構造体のコンストラクタは、要素がマップに追加されたときにレコード番号として使用されるキーを認識する必要があります。 もちろん、これはより多くのコードで行うことができますが、これは私にとって最も優雅に見えます。 は最小限符号化:マップ内の構造体のコンストラクタのアクセスキー
#include <whatever>
struct record
{
string foo;
record(unsigned irec) { foo=readrecord(irec); }
};
map<unsigned,record>recbuf;
int main()
{
// if the element is not yet in the map, it should be read.
string foo_ten=recbuf[10].foo;
// do something with the result
printf("foo_ten: %s\n",foo_ten.c_str());
return 0;
}
EDIT1:上記のコードは動作しません。 これを動作させる方法はありますか? EDIT2: 私は別のマップを追加mapplusクラスを派生::演算子[]:
template<class _Kty, class _Ty, class _Pr = less<_Kty>, class _Alloc = allocator<pair<const _Kty, _Ty> > >class mapplus :public map<_Kty, _Ty, _Pr, _Alloc>
{
public:
mapped_type& operator[](const _Kty &_Keyval)
{ // find element matching _Keyval or insert with default mapped
iterator _Where = _Mybase::lower_bound(_Keyval);
if (_Where == _Mybase::end()
|| _Mybase::_Getcomp()(_Keyval, _Mybase::_Key(_Where._Mynode())))
_Where = _Mybase::emplace_hint(_Where,
_Keyval,
_Ty(_Keyval));
return (_Where->second);
}
};
これは、作業を行います。私はまだ私が不必要に複雑な方法でこれをしたことを指摘するコメントに興味があります。私はしましたか?あまり苦労せずにやることはできますか?
だから、正確にあなたの質問は何ですか?デフォルトのコンストラクタなしでも動作しますか? –