2

I wanna store objects on vectors. But I do not know why it does not work.

‪#‎include‬ <iostream>
#include <vector>
using namespace std;

I have a Persona class in the Persona.h file. And it only has two method: The default constructor and a method called mensaje(), both are public and it does not have any private member.

#include "Persona.h"

int main()
{
    vector<Persona> personas;
    Persona persona1;
    Persona persona2;

    personas.push_back(persona1);
    personas.push_back(persona2);

    vector<Persona>::const_iterator p;

    for(p = personas.begin(); p <= personas.end(); p++) {

Here is where I get the error message

        p.mensaje();
    }
}

I think problem is the way that I am trying to call 'p'. Is right that I try to use const_iterator instead of any other type?

3
  • p <= personas.end() should be <. Also p is an iterator so you should use ->, not . on the iterator to access the members of the class. Commented Feb 11, 2014 at 4:31
  • Have you looked at any references on how to use iterators?
    – chris
    Commented Feb 11, 2014 at 4:32
  • 1
    @user3286380, It should be !=, really.
    – chris
    Commented Feb 11, 2014 at 4:32

2 Answers 2

3

p is iterator not object itself, you need to dereference it:

(*p).mensaje();

OR

p->mensaje();

And

update:

for(p = personas.begin(); p <= personas.end(); p++) {

to:

for(p = personas.begin(); p != personas.end(); p++) {
                          ^^^^^^
2
  • I does not work .____. The mensaje method is this: void Persona::mensaje() { cout << "Hola desde mensaje()" << endl; } Commented Feb 11, 2014 at 4:38
  • @user3053929 you need to make function const.
    – billz
    Commented Feb 11, 2014 at 5:09
1

You are trying to call a non-const method on a const object (the object referenced by a const iterator). Since the mensaje() method does not modify the object, it should be declared const, like so:

void Persona::mensaje() const;

After you make this change, you should be able to call the method on the const object (reference) returned from the const iterator.

(...in addition to the other syntax errors mentioned in other answers.)

Not the answer you're looking for? Browse other questions tagged or ask your own question.