1

int キーと type の値を持つマップを含む street_map というクラスがありますvector<edge>。メソッドの 1 つで、値へのポインタを初期化してvector<edge>その内容を取得しようとしています。

class street_map {
public:
    explicit street_map (const std::string &filename);
    bool geocode(const std::string &address, int &u, int &v, float &pos) const;
    bool route3(int source, int target, float &distance) const {
        auto it = adjacencyList.find(source);
        vector<edge>* v = &(it->second);
        return true;
    }
private:
    unordered_map<side , vector<segment>> map;
    unordered_map<int, vector<edge>> adjacencyList;
};

vector<edge>* v = &(it->second);はエラーを与えます:

Cannot initialize a variable of type 'vector<edge> *' with an rvalue of type 'const std::__1::vector<edge, std::__1::allocator<edge> > *'

エッジクラスは次のとおりです。

class edge {
    int node;
    string street;
    float length;
    int startingNode;
public:
    edge(int startingNode, int node, string street, float length) {
        startingNode = startingNode;
        node = node;
        street = street;
        length = length;
    }
};

これが const キーワードによるものなのか、const キーワードによるものである場合の修正方法を考えています (const キーワードを保持することになっていますが、他に解決策がない場合はそれを取り除くことができると思います)。

4

1 に答える 1

4

次の 4 つのオプションがあります。

1) ベクトルへのポインタを const にする

ベクトルを変更することはできません。

bool route3(int source, int target, float &distance) const {
        auto it = adjacencyList.find(source);
        const vector<edge>* v = &(it->second);
        return true;
    }

2) adjacencyList を可変にする

mutable は、const 関数から非 const としてアクセスできることを意味します。アクセスの設計に注意を払わないと、これは危険です。

private:
    unordered_map<side , vector<segment>> map;
    mutable unordered_map<int, vector<edge>> adjacencyList;

3) ベクターをコピーする

これにより、オーバーヘッドが大きくなる可能性があり、ベクターに加えられた変更はマップに保存されません。

vector<edge> v = (it->second);

4) 関数を非定数にする

street_mapこの方法では、constが置かれているコンテキストで関数を呼び出すことができないことに注意してください。

bool route3(int source, int target, float &distance) {
        auto it = adjacencyList.find(source);
        vector<edge>* v = &(it->second);
        return true;
    }
于 2015-12-01T16:47:18.967 に答える