map :: emplace()使用自定义值类型

编程入门 行业动态 更新时间:2024-10-08 13:39:25
本文介绍了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()使用自定义值类型

本文发布于:2023-11-28 04:35:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640987.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   类型   map   emplace

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!