如何使用std :: map没有默认构造函数的值? [英] How should std::map be used with a value that does not have a default constructor?

查看:1197
本文介绍了如何使用std :: map没有默认构造函数的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个值类型,我想放入地图。
它有一个很好的默认的复制构造函数,但没有一个默认的构造函数。



我相信只要我离开使用<$ c $



然而,我最终会得到这样的丑陋的结构来实际插入一个对象。
(我认为如果已经有该键的值,则插入失败。)

  [5] = x但没有默认构造

std :: map< int,X> :: iterator it = m.find(5)
if(it!= m.end())
{
m-> second = x;
}
else
{
m-> insert(std :: make_pair(5,x));
}

我相信会扫描地图两次,看起来很丑陋。 / p>

有更整洁/更有效的方法吗?

解决方案

您可以使用标准插入函数简单地插入或覆盖:

  auto p = mymap.insert(std :: make_pair(key,new_value)); 

if(!p.second)p.first-> second = new_value; //如果键已经存在则覆盖值

如果要通过rerference传递元素,显式:

  insert(std :: pair< K& V&>(key,value)); 

如果你有一个typedef的地图像 map_t ,您可以说 std :: pair< map_t :: key_type& map_t :: mapped_type&> ,或这个主题的任何合适的变体。 p>




也许这是最好的包装成助手:

  template< typename Map> 
void insert_forcefully(Map& m,
typename Map :: key_type const& key,
typename Map :: mapped_type const& value)
{
std :: pair< typename Map :: iterator,bool> p = m.insert(std :: pair< typename Map :: key_type const& typename Map :: mapped_type const&>(key,value));
if(!p.second){p.first-> second = value; }
}


I've got a value type that I want put into a map. It has a nice default copy constructor, but does not have a default constructor.

I believe that so long as I stay away from using operator[] that everything will be OK.

However I end up with pretty ugly constructs like this to actually insert an object. (I think insert just fails if there is already a value for that key).

// equivalent to m[5]=x but without default construction

std::map<int,X>::iterator it = m.find(5);
if( it != m.end() )
{
   m->second = x;
}
else
{
  m->insert( std::make_pair(5,x) );
}

Which I believe will scan the map twice, and also looks pretty ugly.

Is there a neater / more efficient way to do this?

解决方案

You can simply "insert-or-overwrite" with the standard insert function:

auto p = mymap.insert(std::make_pair(key, new_value));

if (!p.second) p.first->second = new_value;  // overwrite value if key already exists

If you want to pass the elements by rerference, make the pair explicit:

insert(std::pair<K&, V&>(key, value));

If you have a typedef for the map like map_t, you can say std::pair<map_t::key_type &, map_t::mapped_type &>, or any suitable variation on this theme.


Maybe this is best wrapped up into a helper:

template <typename Map>
void insert_forcefully(Map & m,
                       typename Map::key_type const & key,
                       typename Map::mapped_type const & value)
{
  std::pair<typename Map::iterator, bool> p = m.insert(std::pair<typename Map::key_type const &, typename Map::mapped_type const &>(key, value));
  if (!p.second) { p.first->second = value; }
}

这篇关于如何使用std :: map没有默认构造函数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆