C ++为每个,从向量元素 [英] C++ for each, pulling from vector elements
问题描述
我想要对一个攻击向量做一个foreach,每个攻击都有一个唯一ID ,1-3。
类方法接受1-3的键盘输入。
我试图使用foreach来运行我的元素在m_attack,看看数字是否匹配,如果它
我看到的问题是:
a'for each'语句不能对类型为std :: vector< Attack
的表达式进行操作
$ b b
我是这样完全错了,我有C#的经验,是一种基于我的基础上,任何帮助将不胜感激。
我的代码如下:
在标题中
向量< Attack> m_attack;
在班级
int Player :: useAttack(int input)
{
每个(攻击*攻击m_attack)//问题部分
{
//用于以下操作的伪指令
if(attack-> m_num == input)
{
//对于发现的攻击,损害
attack-> makeDamage ();
}
}
}
如果你的编译器支持基于C ++ 11范围的for循环,那么代码如下:
(auto& attack:m_attack)//通过引用访问以避免复制
{
if(attack-> m_num == input)
{
attack-> makeDamage ();
}
}
您应该使用 const auto & attack
取决于 makeDamage()
的行为。
我假设你在Windows上开发基于你的C#背景和警告消息,在这种情况下基于范围的for循环仅在Visual Studio 2012中可用。如果您在Visual Studio 2010中工作,请参阅 andre的回答使用 std :: for_each
在< algorithm>
标题中找到。
如果您不满意使用 std :: for_each
,您可以使用迭代器循环 m_attack
:
for(auto attack = m_attack.begin(); attack!= m_attack.end(); ++ attack)
{
if(attack-> m_num == input)
{
attack-> makeDamage();
}
}
使用 m_attack.cbegin )
和 m_attack.cend()
以获取 const
迭代器。 b $ b
I am trying to do a foreach on a vector of attacks, each attack has a unique ID say, 1-3.
The class method takes the keyboard input of 1-3.
I am trying to use a foreach to run through my elements in m_attack to see if the number matches, if it does... do something.
The problem I'm seeing is this:
a'for each' statement cannot operate on an expression of type "std::vector<Attack
Am I going about this totally wrong, I have C# experience and is kind of what I'm basing this on, any help would be appreciated.
My code is as follows:
In header
vector<Attack> m_attack;
In class
int Player::useAttack (int input)
{
for each (Attack* attack in m_attack) // Problem part
{
//Psuedo for following action
if (attack->m_num == input)
{
//For the found attack, do it's damage
attack->makeDamage();
}
}
}
If your compiler supports C++11 ranged-based for loops, then the code is as follows:
for (auto &attack : m_attack) // access by reference to avoid copying
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
You should use const auto &attack
depending on the behavior of makeDamage()
.
Side note: I assume you're developing on Windows based on your C# background and warning message, in which case the range-based for loop is only available in Visual Studio 2012. If you are working in Visual Studio 2010, see andre's answer for using std::for_each
found in the <algorithm>
header.
If you are uncomfortable using std::for_each
, you can loop over m_attack
using iterators:
for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
Use m_attack.cbegin()
and m_attack.cend()
to get const
iterators.
这篇关于C ++为每个,从向量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!