C++ 带向量指针的迭代器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10325774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:54:02  来源:igfitidea点击:

iterator with vector pointer

c++vectoriterator

提问by Lefsler

I created a vector of pointers

我创建了一个指针向量

vector<Person*> *personVec = new vector<Person*>();

Person contains:

人包含:

getName();
getAge();

If I try to use the iterator it doesn't work.. Here is how I use it:

如果我尝试使用迭代器它不起作用..这是我如何使用它:

    vector<Person>::iterator it;
    for(it = personVec->begin() ;
        it != personVec->end() ;
        ++it)
    {
        cout << it->getName() << endl;
    }

I tried vector<Person*>::iterator it;but no luck with that either.

我试过了,vector<Person*>::iterator it;但也没有运气。

Thanks.

谢谢。

回答by CiscoIPPhone

The iterator needs to be the same type as the container:

迭代器需要与容器的类型相同:

vector<Person>::iterator it;

should be:

应该:

vector<Person*>::iterator it;

回答by nate_weldon

 vector<Person*> *personVec = new vector<Person*>();

this is a pointer to a vector of person pointers

这是一个指向人物指针向量的指针

vector<Person>::iterator it;
for(it = personVec->begin() ; it != personVec->end() ; ++it)
{
    cout << it->getName() << endl;
}

your iter is declare incorrectly you need an iter to a vector of person pointers

您的 iter 声明错误,您需要一个指向 person 指针向量的 iter

you have an iter to a vector of person s

你有一个对 person s 向量的迭代

vector<Person*>::iterator it;
for(it = personVec->begin() ; it != personVec->end() ; ++it)
{
    cout << (*it)->getName() << endl;
}

http://www.cplusplus.com/reference/std/iterator/

http://www.cplusplus.com/reference/std/iterator/

and

http://www.cplusplus.com/reference/stl/vector/begin/

http://www.cplusplus.com/reference/stl/vector/begin/