取消引用 std::vector 个对象指针的每个元素

De-Referencing each element of an std::vector of pointers to objects

假设我有一个名为 TextEntry 的 class,带有一些实例变量和一个方法 ask()(其中 returns 是一个整数)。

然后我创建一个类型的向量:std::vector<TextEntry*> d_textTextEntry 类型的指针向量)。我希望遍历此向量中的所有元素并调用应用于每个元素的方法 ask()。这是正确的做法吗?

for (std::vector<TextEntry*>::iterator it = d_text.begin(); it != d_text.end(); ++it) {

    TextEntry* TextEntryPointer = *it; // first dereference the iterator 

    TextEntry TextEntry = *TextEntryPointer; // dereference the TextEntry pointer

    int j = TextEntry.ask();

}

无论出于何种原因,此实现都会给我一个错误,因此了解原因是上述代码还是我项目其余部分的其他问题会很有帮助。

I wish to iterate over all the elements in this vector and call the method ask() applied to each element. Is this the correct way to do it?

差不多。

您的程序不会在 d_text 指向的任何元素上调用 ask,而是在每个指向的元素的副本上调用。


I am confused why it is a copy.

您创建了一个 TextEntry 类型的变量。您从 *TextEntryPointer 复制初始化它。这就是为什么有一个副本。

Is there a way to call it on the original element?

是的。您可以使用引用变量代替复制构造 TextEntry 变量:

TextEntry& TextEntry = *TextEntryPointer;

这是指vector中元素指向的对象。

或者更简单地说,根本不创建中间变量:

int j = TextEntryPointer->ask();

也许连指针都不行:

int j = (*it)->ask();

您也可以简化循环:

for(TextEntry* ptr : d_text) {
    int j = ptr->ask();
}

For whatever reason this implementation is giving me an error

少了一个分号

TextEntry TextEntry = *TextEntryPointer // dereference the TextEntry pointer

PS。避免使用与类型相同的标识符来命名变量。

一个带有少量假设的示例程序。 查看调用成员函数的主函数。

 #include <iostream>
    #include <vector>

using namespace std;

class TextEntry
{
    public:

    int ask()
    {

       return 1;

    }

};

int main()
{
    vector<TextEntry*> te;

    TextEntry* te1 = new TextEntry();
    TextEntry* te2 = new TextEntry();
    TextEntry* te3 = new TextEntry();
    TextEntry* te4 = new TextEntry();

    te.push_back(te1);
    te.push_back(te2);
    te.push_back(te3);
    te.push_back(te4);

    for (std::vector<TextEntry*>::iterator it = te.begin(); it != te.end(); ++it) 
    {
        TextEntry *t = *it;
        cout<<t->ask();

    }

}

其他答案正确。但是我们现在是 2016 年,所以我们有 c++11:

for (auto& text_entry_ptr: d_text)
{
    int j = text_entry_ptr->ask();
}

更简单、更清晰。