简体   繁体   中英

difference between indexing of lists and vectors

While attempting to replace code using lists which was implemented with vectors and was working fine with vectors, I see error c2227 list of ->set_as_output' must point to class/struct/union/generic type. I have provide both implementations below

class pin {
    friend class gate;
    pin(){}
    ~pin() {}
public:
   void set_as_input();
   void set_as_output();

}; // class pin


class gate {

protected:
    std::list<pin *> pins_;
    //std::vector<pin *> pins_;
    gate();
    ~gate();
    virtual bool validate_structural_semantics();
public:

}; // class gate

class and_gate : public gate
{
     bool validate_structural_semantics();
public:
}; // class and_gate

bool and_gate::validate_structural_semantics()
{
    if (pins_.size() < 3) return false;
    //pins_[0]->set_as_output();//using vectors and works fine
    pins_.begin ->set_as_output();//error is here with lists
    //for (size_t i = 1; i < pins_.size(); ++i)
    for (std::list<pin *>::iterator iter = pins_.begin();
        iter != pins_.end(); ++iter)
        //pins_[i]->set_as_input();
        (*iter)->set_as_input();
    return true;
}

I wanted to learn what is difference between lists and vectors in implementation and what is missing in my code as far as lists are concerned to solve the issue. How to solve it?

lists do not have the [] operator, they are not random access containers.

You could use auto iter=std::advance(pins_.begin(), ndx); to get an iterator to the ndx'th element of a list.

pins_.begin ->set_as_output();

begin is a member function; you have to call it. And just as you've done with (*iter)->set_as_input() you need to dereference the iterator to get a pointer:

(*pins_.begin())->set_as_output();

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