简体   繁体   中英

Struct does not provide a subscript operator

I'm trying to loop through my adjacency list in my DFS search class, but its giving me this error: type 'AdjList' does not provide a subscript operator. I feel like it might be the way i saved adjList constructor for DFS but I'm not sure. I saw other solutions saw it has to be passed as a pointer so I changed AdjList list in the constructor to AdjList* list but that did not work. Here is my code:

main.cpp


    AdjList::AdjList(){}

    AdjList::AdjList(vector<Node> nodeVector){
        nodeContainer = nodeVector;
    }

    void AdjList::makeAdjList(){
        int temp;
        for(int i = 0; i < nodeContainer.size(); i++){
            connections = nodeContainer[i].getConnectionsVector();

            for(int x = 0; x < connections.size(); x++){
            innerList.push_back(nodeContainer[connections[x] - 1]);
            }
        
        adjList.push_back(innerList);
        innerList.clear();
        }  
    }

    //other AdjList functions

int main(){
    vector<Node> nodeContainer;
    nodeContainer = load();

    
    AdjList adjList(nodeContainer);
    adjList.makeAdjList();
   
    
    DFS search(nodeContainer, adjList);
    search.iterative(6,3);

}

DFS.cpp

DFS::DFS(vector<Node> nodeVec, AdjList list){
        nodeContainer = nodeVec;
        adjList = list;
   }

vector<Node> DFS::iterative(int src, int dest){
        vector<Node> vectorPath;
     
            
            list<Node>::iterator it;
            int i = 6;
            for(it = adjList[i].begin(); it != adjList[i].end(); it++){ //this is where the 
                                                                        //error is happening
                cout << it->getNodeID() << " ";
            } 
        return vectorPath;
    }

AdjList.h

class AdjList{
private:
public:
    list<Node> innerList;
    vector<list<Node> > adjList;
    vector<Node> nodeContainer;
    vector<int> connections;
    int temp;

    AdjList();
    AdjList(vector<Node> nodeVector);

    void makeAdjList();

    void displayAdjList();
};

When you say adjList[i] , C++ looks for an operator[] in the type of adjList which is AdjList . As this type doesn't have such a member function you get the error message that it's missing.

Supply a

std::list<Node>& operator[](std::size_t i);
std::list<Node> const& operator[](std::size_t i) const;

and return adjList[i] in both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM