c++ - 无法转换 'std::optional' 到 '__gnu_cxx::__alloc_traits>::value_type {aka char}'
问题描述
我正在尝试实现一个图,其中边由存储在向量向量中的可选对象表示。尝试插入边缘时出现以下错误:
错误:不能在赋值中将 'std::optional<int>' 转换为 '__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type {aka char}' vertices_.at(vertex1_id)[vertex2_id] = opt;
这是我的代码,有 2 个不起作用的示例,我不知道为什么。
vector<vector<optional<E>>> edges_; // this is adjacency matrix
vector<V> vertices_;
void Graph<V,E>::insertVertex(const V &vertex_data) {
this->vertices_.push_back(vertex_data);
this->edges_.emplace_back(vector<optional<E>>());
int k = this->edges_.size() - 2;
int num_of_optionals_to_add = 1; // below I adjust matrix size and fill with empty optionals
while(k >= 0) {
for(int i = 0; i < num_of_optionals_to_add; i++ ) {
this->edges_[k].emplace_back(optional<E>());
}
num_of_optionals_to_add++;
}
}
void Graph<V,E>::insertEdge(std::size_t vertex1_id, std::size_t vertex2_id, E edge) {
optional<E> opt(edge);
vertices_[vertex1_id][vertex2_id] = opt; // error here
}
//alternative version, also doesn't work..
void Graph<V,E>::insertEdge(std::size_t vertex1_id, std::size_t vertex2_id, E edge) {
vertices_[vertex1_id][vertex2_id].value(edge);
}
// TEST
Graph<std::string, int> g;
g.insertVertex("V1");
g.insertVertex("V2");
g.insertVertex("V3");
g.insertVertex("V4");
g.insertEdge(0, 0, 1);
解决方案
vertices_[vertex1_id][vertex2_id] = opt;
大概应该是:
edges_[vertex1_id][vertex2_id] = opt;
推荐阅读
- json - 角度启动错误 npm ERR!代码生命周期
- javascript - javascript函数传递具有空值的对象
- python-3.x - 如何修复:cx_Oracle.DatabaseError:DPI-1047:找不到 64 位 Oracle 客户端库 - Python
- javascript - 如何在javascript中将数据从旧json复制到新json?
- php - shell_exec 可以运行我的机器学习代码吗?它在终端上运行良好,但在 shell_exec 中返回 NULL
- c# - NET Core 跨 Docker 服务副本同步变量值
- openvpn - Mikrotik 多站点 OpenVPN。客户不可见
- javascript - AWS:尝试加载预签名 URL 时拒绝访问(直接文件上传浏览器)
- css - 向动态创建的组件添加样式
- python - Pandas assignment vs inplace=True on .loc?