访问作为类向量的元素的对象的成员函数

Accessing the member function of an object which is an element of the vector of class

本文关键字:元素 对象 成员 函数 向量 访问      更新时间:2023-10-16

参考下面的代码(只是一个示例),是否可以使用迭代器 i 还是我必须使用另一个变量来保持元素索引的计数?

   class Cdata
    {
    public : 
    int a = 0;
    //constructor
    //destructor
    setCdata();
    }
    void main()
    {
       vector<CData> dat;
       dat.push_back(1);
       dat.push_back(2);
       dat.push_back(3);
        //Define an iterator
        vector<CData>::iterator i;
        for(i = cl.begin(); i != cl.end(); i++)
        {
            dat[count].setCdata(); //is there a way of accessing the print() by using just the iterator i??     
            count++;
        }
    }

是的,您可以简单地使用以下方法之一:

i->setCdata();
(*i).setCdata();

请注意,在 C++11 中,您还可以使用以下表示法:

for(auto& e : cl)
    e.setCdata();