无法将'std :: optional <int>'转换为'__gnu_cxx :: __ alloc_traits <std :: allocator <char>> :: value_type {aka char}'

时间:2019-04-16 18:00:41

标签: c++ graph optional

我正在尝试实现一个图形,其中边缘由存储在矢量向量中的可选对象表示。尝试插入边线时出现以下错误:

error: cannot convert 'std::optional<int>' to '__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type {aka char}' in assignment
     vertices_.at(vertex1_id)[vertex2_id] = opt;

这是我的代码,其中有两个无效的示例,我也不知道为什么。

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);

1 个答案:

答案 0 :(得分:0)

vertices_[vertex1_id][vertex2_id] = opt;

应该是:

edges_[vertex1_id][vertex2_id] = opt;