【发布时间】:2016-10-13 14:46:13
【问题描述】:
用例:记录缓冲区。这是基本的想法。 使其工作需要记录结构的构造函数知道在将元素添加到映射时用作记录编号的键。 当然,这可以用更多的代码来完成,但这对我来说看起来最优雅。 最少编码:
#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:上面的代码不起作用。 任何想法如何让它发挥作用? 编辑2: 我派生了一个 mapplus 类,添加了另一个 map::operator[]:
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);
}
};
这确实有效。我仍然对 cmets 向我指出我以不必要的复杂等方式这样做很感兴趣。我有吗?可以少花些功夫吗?
【问题讨论】:
-
那么您的问题到底是什么?它甚至可以在没有默认构造函数的情况下工作吗?
标签: c++ dictionary