首页 > 解决方案 > 无法转换 '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);

标签: c++graphoptional

解决方案


vertices_[vertex1_id][vertex2_id] = opt;

大概应该是:

edges_[vertex1_id][vertex2_id] = opt;

推荐阅读