Hello

I have an abstract class called Number and a simple derived class called Double, which has a private variable value and a function called getValue() which returns the value;

I also have a vector of pointers of type Number which are pointing to Double.

code:

...
vector<Number*> v1;
v1.push_back(new Double(2.3));
v1.push_back(new Double(1.4));
...

I'm trying to print the values with a foor loop, with a vector<Number*>::iterator, using begin() and end() member function but i can't get it to work.

I tried it like this but it's obviously wrong:

vector<Number*>::iterator j;
for(int j=v1.begin(); j<v1.end(); j++)
cout<<v1.at(*j)->getValue();

What should i change?

Get rid of the int.

You have two variables named 'j' there: your iterator, and an int local to the for loop.

vector<Number*>::iterator j;
for (j = v1.begin(); j<v1.end(); j++)
  cout<<v1.at(*j)->getValue();

Don't forget proper indentation!

Hope this helps.

Oh, i made a typo with that int. I don't have it in my code ofcourse, so basicly ignore it. It doesn't work without it either.

Er, sorry, I wasn't paying enough attention. Don't use at().

cout << j->getValue();

Hope this helps.

Ok here's the whole code:

#include <iostream>
#include <vector>
using namespace std;

class Number
{
     public:
           Number(){}
           ~Number(){}
           virtual double getValue()=0;
};

class Double : public Number
{
      private:
           double value;
      public:
            Double(double v):value(v){}
            ~Double(){}
            double getValue(){return value;}
};

int main()
{
      vector<Number*> v1;
      v1.push_back(new Double(2.3));
      v1.push_back(new Double(1.4));
      vector<Number*>::iterator j;
      for(j=v1.begin(); j<v1.end(); j++)
             cout<<j->getValue()<<endl;
      return 0;
}

Argh. I'm so sorry. There is something wrong... Your base type is a pointer, and the iterator is a pointer, so you need to dereference it twice (and I had you doing it only once... cout << (*j)->getValue() << endl; Sorry... :$

Doesn't work :( .

Next time, at least put in minimal effort and post an error or something; instead of other people repeatedly posting suggestions, and you just saying "doesn't work" each time without any clue as to what doesn't work.

This article has been dead for over six months. Start a new discussion instead.