访问作为类向量的元素的对象的成员函数
Accessing the member function of an object which is an element of the vector of class
参考下面的代码(只是一个示例),是否可以使用迭代器 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();
相关文章:
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- 为什么平均打印数组元素比打印单个对象慢C++?
- push_back通过自行创建的对象获取最后一个元素的向量
- 从自定义类获取对象向量中的 max 元素
- 选择一个元素而不是一个对象的数组的原因
- 数组对象的生存期是否在重用其元素存储时结束?
- 如何替换双端对象中的元素?
- 打印出对象向量中的每个元素C++
- C++ - 打印派生类对象的矢量<base*> 元素
- 从C++中的非基元对象的向量中移除所有匹配元素
- 如何将某个元素从shared_ptr擦除到对象向量?
- 从对象数组中删除元素
- 访问指向对象指针向量的指针的第一个元素?
- 在指向对象的指针的动态数组上插入新元素
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- 如何通过引用对用户定义对象的类型集 (STL) 的数组元素进行增强迭代?
- 如何从对象指针的向量中正确清理元素
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 如何遍历 QStack 对象的元素
- 在父类的构造函数中调用元素对象的构造函数