I've got this:

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <sstream>

using namespace std;

class alfa{
	private:
		int x;
	public:
		alfa(){
			cout<<"Dimiourgithike ena alfa"<<endl;
			x=rand()%10;
		}
		~alfa(){
			cout<<"Katastrafike ena alfa"<<endl;
		}
	void get_x(){
		cout<<"To x exei timi: "<<x<<endl;
	}
};

int main(){
	alfa* alfadi;
	int no;
	cout<<"Dose enan arithmo"<<endl;
	cin>>no;
	vector<alfa> alfadia;
	for(int i=0;i<no;i++){
		alfadi=new alfa;
		alfadia.push_back(alfadi);
	}
}

But i get error on push_back() while compiling.Any ideas?

>> But i get error on push_back() while compiling.

The alfadia vector stores objects of type alfa , not pointers to such objects. Then again new alfa returns a pointer to the allocated alfa object.

So, if you want to store objects ...

// vector for storing objects ...
vector<alfa> alfadia;
for(int i=0;i<no;i++)
{
  // 'obj' below, is constructed via default ctor
  alfa obj;
  alfadia.push_back(obj);
}

And if you want to store pointers to objects ...

// vector for storing pointers ...
vector<alfa * > alfadia;
for(int i=0;i<no;i++)
{
  // allocate one alfa object constructed via default ctor
  alfa * obj_pointer = new alfa;
  alfadia.push_back(obj_pointer);
}

or u can change to..

alfadia.push_back(*alfadi);

i think.....

or u can change to..

alfadia.push_back(*alfadi);

Yes, that will push a copy-constructed object onto the vector, however, the object pointed by alfadi has to be deleted to avoid leaking memory.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.