map :: emplace()使用自定义值类型 [英] map::emplace() with a custom value type

查看:968
本文介绍了map :: emplace()使用自定义值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用 map :: emplace()。任何人都可以帮助我找出正确的语法使用?我有效地尝试做与此示例中相同的操作。这是我的版本:

  #include< map& 
using namespace std;

class Foo
{
// private members

public:
Foo(int,char,char)/ *:init ),member()* / {}

//没有默认ctor,copy ctor,move ctor或赋值
Foo()= delete;
Foo(const Foo&)= delete;
Foo(Foo&&)= delete;
Foo& operator =(const Foo&)= delete;
Foo& amp; operator =(Foo&&)= delete;
};


int main()
{
map< int,Foo> mymap;
mymap.emplace(5,5,'a','b');

return 0;
}

根据GCC 4.7(与 -std = c ++ 11 标志),我错误地在 emplace 行。上面链接的示例不会说明如何处理自定义类型而不是原语。

解决方案

容器的 emplace 成员使用提供的参数构造一个元素。



您的地图的 value_type std :: pair< const int,Foo& ,并且该类型没有构造函数接受参数 {5,5,'a','b'} / p>

  std :: pair< const int,Foo>值{5,5,'a','b'}; 
map.emplace(value);

您需要调用 emplace 匹配的构造函数之一。



使用符合C ++ 11的实现,您可以使用: p>

  mymap.emplace(std :: piecewise_construct,std :: make_tuple(5),std :: make_tuple(5,'a' 'b')); 

但是GCC 4.7不支持该语法(GCC 4.8将在发布时) p>

I'm having trouble using map::emplace(). Can anyone help me figure out the right syntax to use? I am effectively trying to do the same thing as in this example. Here is my version:

#include <map>
using namespace std;

class Foo
{
  // private members

  public:
    Foo(int, char, char) /* :init(), members() */ {  }

    // no default ctor, copy ctor, move ctor, or assignment
    Foo() = delete;
    Foo(const Foo&) = delete;
    Foo(Foo &&) = delete;
    Foo & operator=(const Foo &) = delete;
    Foo & operator=(Foo &&) = delete;
};


int main()
{
  map<int, Foo> mymap;
  mymap.emplace(5, 5, 'a', 'b');

  return 0;
}

Under GCC 4.7 (with the -std=c++11 flag), I am erroring out on the emplace line. The example I linked above doesn't say anything about how to deal with custom types instead of primitives.

解决方案

A container's emplace member constructs an element using the supplied arguments.

The value_type of your map is std::pair<const int, Foo> and that type has no constructor taking the arguments { 5, 5, 'a', 'b' } i.e. this wouldn't work:

std::pair<const int, Foo> value{ 5, 5, 'a', 'b' };
map.emplace(value);

You need to call emplace with arguments that match one of pair's constructors.

With a conforming C++11 implementation you can use:

mymap.emplace(std::piecewise_construct, std::make_tuple(5), std::make_tuple(5, 'a', 'b'));

but GCC 4.7 doesn't support that syntax either (GCC 4.8 will when it's released.)

这篇关于map :: emplace()使用自定义值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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