C++ 遍历指针向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23318875/
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-28 00:24:54  来源:igfitidea点击:

Iterating through a vector of pointers

c++pointersobjectvector

提问by Red Shift

I'm trying to iterate through a Players hand of cards.

我正在尝试遍历玩家手中的牌。

Player.cpp

播放器.cpp

vector<Card*>::iterator iter;
    for(iter = current_cards.begin(); iter != current_cards.end(); iter++) {
        cout << iter->display_card() << endl;
    }

The iter in

迭代器

cout << iter->display_card() << endl;

currently comes up with the "error: Expression must have pointer-to-class type".

当前出现“错误:表达式必须具有指向类的类型”。

Likewise, current_cards is declared with:

同样, current_cards 声明为:

vector<Card*>current_cards;

Furthermore, the display_card() method is simply:

此外, display_card() 方法很简单:

Card.cpp

卡.cpp

string Card::display_card(){
    stringstream s_card_details;
    s_card_details << "Colour: " << card_colour << "\n";
    s_card_details << "Type: " << card_type << "\n";

    return s_card_details.str();
}

I have looked over various resources and everything that has been suggested for similar types of issues hasn't worked for me. Thanks for any help!

我查看了各种资源,针对类似问题提出的所有建议都对我不起作用。谢谢你的帮助!

回答by Reto Koradi

Try this:

尝试这个:

cout << (*iter)->display_card() << endl;

The *operator gives you the item referenced by the iterator, which in your case is a pointer. Then you use the ->to dereference that pointer.

*运营商给你的迭代器,而你的情况是一个指针引用的项目。然后您使用->来取消引用该指针。

回答by Joky

You have to dereference the iterator to access the pointer:

您必须取消引用迭代器才能访问指针:

#include <vector>
#include <iostream>

class Card {
public:
  std::string display_card();
};


int main() {
  std::vector<Card*>current_cards;
  std::vector<Card*>::iterator iter, end;
  for(iter = current_cards.begin(), end = current_cards.end() ; iter != end; ++iter) {
    std::cout << (*iter)->display_card() << std::endl;
  }
}

Another observation is the iter++which you should avoid in profit of ++iter(see https://stackoverflow.com/a/24904/2077394). Depending on the container, you may also want to avoid calling end() each iteration.

另一个观察结果是iter++您应该避免的利润++iter(参见https://stackoverflow.com/a/24904/2077394)。根据容器的不同,您可能还希望避免每次迭代都调用 end()。

(By the way it always help to provide a minimal reproducible example like I just wrote when you ask question.)

(顺便说一句,提供一个最小的可重复示例总是有帮助的,就像我刚才在你提问时写的那样。)

回答by Rakib

De-referencing the iterator by iter-> gives a pointer to an object of type Card, you have to write (*iter)->display_card();

通过 iter-> 取消引用迭代器给出一个指向 Card 类型对象的指针,您必须编写 (*iter)->display_card();