如何(是否可能)在C ++中使用迭代器访问类成员?

时间:2014-08-26 16:10:23

标签: c++ vector iterator

之前,当使用普通的for-loop时,我会像这样访问它:

this->customClassCustomVectorArray[i]->getCustomMember();

但现在我不知道如何访问它,因为当我键入“ - >”时VS2010不提供任何成员或方法。

for(vector<CustomClass*>::iterator it = this->customClassCustomVectorArray.begin(); it != this->customClassCustomVectorArray.end(); ++it){
    cout << this->customClassCustomVectorArray[*it]->getCustomMember() << endl;
}

我试过“*它”和“它”,但没有任何反应。这甚至可能吗?我想它应该是。

3 个答案:

答案 0 :(得分:4)

cout << this->customClassCustomVectorArray[*it]->getCustomMember() << endl;

这是不对的。期望向量中包含数字索引,但[]不是数字索引。它是一个迭代器。它已经指向向量中的正确位置。

*it

cout << (*it)->getCustomMember() << endl; 仅适用于使用数字索引而不是迭代器进行迭代的时候。

答案 1 :(得分:2)

错:

this->customClassCustomVectorArray[*it]->getCustomMember()

右:

(*it)->getCustomMember()

为什么呢?因为it非常像

this->customClassCustomVectorArray + i

事实上,它与

完全相同
this->customClassCustomVectorArray.begin() + i

所以你不需要说

this->customClassCustomVectorArray

两次。

答案 2 :(得分:0)

尽管@ Lightness的答案是正确的,但它仍然没有指向你应该如何做到这一点。大多数情况下,您使用迭代器编写显式循环,这是一个错误(这也不例外)。 std::endl的大多数用法也是错误(在这方面看起来也不例外)。

所以,不是编写一个显式循环,而是显式地解引用迭代器等,最后采取他的建议(尽管它是正确的)来使语法正确,你应该考虑摆脱基本上所有其中,并使用通用算法来完成工作。

在这种情况下,您有一个输入集合。对于该输入集合中的每个项目,您将调用一个函数,然后将结果写入某个输出集合。这几乎描述了std::transform,所以它可能适合手头的工作。

std::transform(customClassCustomVectorArray.begin(),
               customClassCustomVectorArray.end(),
               mem_fun(&customClass::customMember),
               std::ostream_iterator<result_type>(std::cout, "\n"));

这使用result_type来表示调用成员函数的结果类型。必须明确指明结果类型是这种技术的一种责任,但至少IMO,其优势远远超过轻微责任。

最明显的优势可能是std::transform的定义是(合理地)众所周知和标准化的,所以任何了解C ++(好吧)的人都会立即对这应该做的事情有一个非常公平的想法作为一个整体 - 在一个范围内的每个项目上调用一些函数,并将返回的值写入某个目标。