[c++] C++ for each, pulling from vector elements

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();
        }
    }
}

This question is related to c++ for-loop vector each

The answer is


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);

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.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to vector

How to plot vectors in python using matplotlib How can I get the size of an std::vector as an int? Convert Mat to Array/Vector in OpenCV Are vectors passed to functions by value or by reference in C++ Why is it OK to return a 'vector' from a function? Append value to empty vector in R? How to initialize a vector with fixed length in R How to initialize a vector of vectors on a struct? numpy matrix vector multiplication Using atan2 to find angle between two vectors

Examples related to each

jQuery animated number counter from zero to value How to iterate over array of objects in Handlebars? Excel VBA For Each Worksheet Loop jQuery looping .each() JSON key/value not working jQuery '.each' and attaching '.click' event How to use continue in jQuery each() loop? jQuery .each() with input elements C++ for each, pulling from vector elements jQuery each loop in table row Get href attribute on jQuery