Moncheeta
Moncheeta

Reputation: 95

Why can't I access the members of a element in a vector

void remove_attack(std::string name) {
    if (!attacks.empty()) {
        for (auto it = attacks.begin(); it != attacks.end(); ++it) {
            if (*it.name == name) {
                attacks.erase(it);
                break;
            }
        }
    }
}

This function is trying to remove an attack from a vector named attacks that hold attack structures.

struct attack { 
    std::string name = "None";
    unsigned int damage = 0;
    std::string desc = "None";
};

The vector looks like: std::vector<attack> attacks;

When I try to compile:

main.cpp:52:41: error: ‘class __gnu_cxx::__normal_iterator<attack*, std::vector<attack> >’ has no member named ‘name’
   52 |                                 if (*it.name == name) {
      |       

I don't understand what I am doing wrong.

Upvotes: 1

Views: 86

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

You need to write

if ( ( *it ).name == name) {

or

if ( it->name == name) {

As for the function then it should be declared and defined the following way

#include <vector>
#include <iterator>
#include <algorithm>

//...

void remove_attack( const std::string &name ) 
{
    auto it = std::find_if( std::begin( attacks ), std::end( attacks ),
                            [&]( const auto &a )
                            {
                                return a.name == name;
                            } );    

    if ( it != std::end( attacks ) ) attacks.erase( it );
}

Upvotes: 1

Related Questions