在 std::map 中插入非默认构造元素

Insert non-default constructed element in std::map

本文关键字:默认 元素 插入 std map      更新时间:2023-10-16

这可能是一个该死的直截了当的问题。但我似乎无法将我的对象插入地图。我很确定我不必定义自己的复制构造函数,因为我只使用标准的东西。现在感觉就像把头撞在墙上:lol:,这是我正在尝试创建的地图:

map<unsigned, Vertex> vertexes;

顶点头文件:

#ifndef KNOTSV2_VERTEX_H
#define KNOTSV2_VERTEX_H
#include <forward_list>
#include <set>
#include <iostream>
#include "VertexType.h"
using namespace std;
// Defines.
typedef tuple<edge_list, edge_list, edge_list> neigh_set_entry;

/*
* Matching
*/
struct match_first {
match_first(unsigned value) : value(value) {};
template<class A>
bool operator()(const pair<unsigned, A> &a) {
return a.first == value;
}
private:
unsigned value;
};

class Vertex {
public:
/*
* Constructors
*/
Vertex(unsigned identifier, VertexType *type, unsigned attributes) : identifier(identifier), type(type), values(attributes_vec(attributes)) {};
// Methods ..
private:
/*
* Members
*/
unsigned identifier;
attributes_vec values;
VertexType *type;
vector<pair<unsigned, neigh_set_entry>> neigh_set;
};

我正在尝试调用的函数:

Vertex& Graph::create_vertex(VertexType &type) {
Vertex v(id_enumerator++, &type, type.num_attributes());
return vertexes[id_enumerator] = v;
}
注意:在实例化成员函数"std::__1::

map"时,此处请求 std::__1:分配器>>::operator[]">

return vertexes[id_enumerator] = v;
^
注意:候选构造函数

(隐式移动构造函数)不可行:需要 1 个参数,但提供了 0 个参数

class Vertex {
^

注意:候选构造函数(隐式复制构造函数)不可行:

注意:候选构造函数不可行:需要 3 个参数,但提供了 0 个参数 顶点(无符号标识符, 顶点类型 *类型, 无符号属性) : 标识符(标识符), 类型(类型), 值(attributes_vec(属性)) {};

所以我理解这是因为它试图调用"普通构造函数",但我不想为传递给构造函数的值创建 getter 和 setter;因为它们可能不会被更改。作为第二次尝试,我尝试使用map::emplace,但也没有运气。除了创建普通构造函数之外,还有其他选择吗?

尝试放置和插入以及成对构造,也没有运气。

Vertex& Graph::create_vertex(VertexType &type) {
//Vertex v();
return vertexes.insert(make_pair(id_enumerator, Vertex(id_enumerator, &type, type.num_attributes()))).first->second;
}
Vertex& Graph::create_vertex(VertexType &type) {
//Vertex v();
return vertexes.emplace(id_enumerator, Vertex(id_enumerator, &type, type.num_attributes())).first->second;
}
Vertex& Graph::create_vertex(VertexType &type) {
//Vertex v();
return vertexes.emplace(piecewise_construct, forward_as_tuple(id_enumerator), forward_as_tuple(id_enumerator, &type, type.num_attributes())).first->second;
}

阅读std::map::emplace的文档:

新元素的构造函数(即std::pair<const Key, T>) 的调用参数与提供给 emplace 的参数完全相同,通过std::forward<Args>(args)...转发。

struct Vertex 
{
Vertex(unsigned identifier, int type, unsigned attributes) {}
};
int main()
{
std::map<unsigned, Vertex> vertexes;
//                       Vertex
//                       vvvvvvvvvvvvvvvvv
vertexes.emplace(0u, Vertex{0u, 1, 0u});
//                   ^^
//       const unsigned
}

活魔杖盒示例