对于每个元素,从向量元素中提取

我正在尝试对一个攻击矢量进行搜索,每次攻击都有一个 唯一身份,比如1-3。

Class 方法接受1-3的键盘输入。

我正在尝试使用 foreach 来遍历 m _ hack 中的元素,以查看数字是否匹配,如果匹配... ... 做一些事情。

我看到的问题是:

a'for each' statement cannot operate on an expression of type "std::vector<Attack

我是不是完全搞错了,我有 C # 经验,这也是我的基础,如果有任何帮助,我会很感激的。

我的代码如下:

在头部

vector<Attack> m_attack;

在课堂上

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();
}
}
}
353937 次浏览

This is how it would be done in a loop in C++(11):

   for (const auto& attack : m_attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}

There is no for each in C++. Another option is to use std::for_each with a suitable functor (this could be anything that can be called with an Attack* as argument).

C++ does not have the for_each loop feature in its syntax. You have to use c++11 or use the template function std::for_each.

struct Function {
int input;
Function(int input): input(input) {}
void operator()(Attack& attack) {
if(attack->m_num == input) attack->makeDamage();
}
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);

For next examples assumed that you use C++11. Example with ranged-based for loops:

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().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
[](Attack * attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
);

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.

The for each syntax is supported as an extension to native c++ in Visual Studio.

The example provided in msdn

#include <vector>
#include <iostream>


using namespace std;


int main()
{
int total = 0;


vector<int> v(6);
v[0] = 10; v[1] = 20; v[2] = 30;
v[3] = 40; v[4] = 50; v[5] = 60;


for each(int i in v) {
total += i;
}


cout << total << endl;
}

(works in VS2013) is not portable/cross platform but gives you an idea of how to use for each.

The standard alternatives (provided in the rest of the answers) apply everywhere. And it would be best to use those.