简体   繁体   English

列表索引和向量索引之间的区别

[英]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.在尝试使用用向量实现的列表替换代码时,我看到错误 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);您可以使用 auto iter=std::advance(pins_.begin(), ndx); to get an iterator to the ndx'th element of a list.获取到列表中第 ndx 个元素的迭代器。

pins_.begin ->set_as_output();

begin is a member function; begin是一个成员函数; 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:就像您对(*iter)->set_as_input()所做的一样,您需要取消引用迭代器以获取指针:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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