Thread: How to access a dynamic array inside a std::set ?

  1. #1
    Registered User IndioDoido's Avatar
    Join Date
    Apr 2007
    Posts
    194

    How to access a dynamic array inside a std::set ?

    hi once again!

    it seems like this week i'm going to beak the record of the "biggest number of threads created by a single user"

    i've created a class grocery and class for the data of the products ordered:
    Code:
    class grocery
    {
    	dataProdOrder *prod;
    	unsigned int num;//num of elements in array
    
    	string idOrder;
    	string nameClient;
    	unsigned int totalPrice;
    	
    	
    	public:
    		...
    }
    
    class dataProdOrder
    {
    	string idP; //id of the product to order
    	unsigned int quant; //quantity of each product to order 
    	
    	public:
    		...
    	
    };
    I think i managed to save everything correctly inside a std::set, but now i need to see the product orders.
    How can i do the following from the orders std::set?

    Cliente Name: Ricky
    Order ID: 123R

    Products Ordered: //from the dataProdOrder *prod;
    - 123BRD QT:2 //from the dataProdOrder *prod;
    - 546DRA QT:1 //from the dataProdOrder *prod;
    ...

    Total Price: 20€
    "Artificial Intelligence usually beats natural stupidity."

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Your question is not clear.

    >> think i managed to save everything correctly inside a std::set,

    and then

    >> - 123BRD QT:2 //from the dataProdOrder *prod;

    prod is a pointer to a dataProdOrder or possibly a dynamically allocated array
    So what is it ?
    Kurt

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I see no std::set. You'd just loop over each product and print the needed information.

    You may need to move DataProdOrder before Grocery (or use forward declaration) as it is referenced there.

    I also suppose that knowing what the public part looks like might be necessary. And where does the total price come out of?
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> I'm getting a bunch of errors
    What are the errors? Where in the code do they point to?

    You need an operator+= for your orders class. That operator+= needs to create a new array with a bigger size, then copy the contents of prod, then add the new order to the end, then delete the original prod, and finally make prod point to the new array.

    This is a complicated process, do you have any of it done?

    By the way, this has nothing to do with std::set. Your orders class has a dynamic array, and you need to add code to maintain that. Normally you would use a vector (or set or something else) but your instructor is asking you to learn how to manage a dynamic array.

  5. #5
    Registered User IndioDoido's Avatar
    Join Date
    Apr 2007
    Posts
    194
    hi Daved, and thanks...
    this is what i've changed in my code:

    sorry i didn't translate it...but if you don't understand i'll do it.

    make order function:
    Code:
    void mercearia::criarEncomenda(encomendas *E) 
    {
    	string nome, idE, idP;
    	unsigned int quant=0, precoT=0, numP=0, preco;
    	char op='s';
    	
    	cout<<"\nQual o nome do comprador: ";
    	getline(cin, nome);
    
    	cout<<"\nInsira um ID para a encomenda: ";
    	getline(cin, idE);
    
    
    	while(op!='n')
    	{
    		cout<<"\nInsira o ID do produto a encomendar: ";
    		getline(cin,idP);
    		fflush(stdin);
    		
    		preco = verExProd(idP);
    
    		if(preco == -1)
    		{
    			cout<<"Produto nao existe!";
    		}	
    		else
    		{
    			numP++;
    			cout<<"\nInsira a quantidade a encomendar: ";
    			cin>>quant;
    
    			//encomendas enc;
    			dadosProdEnc p(idP,quant);
    			preco *= quant;
    			*E += p; //operador do array de produtos da encomenda
    
    			precoT += preco; //operador por defeito
    			
    			E->setIDEnc(idE);
    			E->setNome(nome);
    			E->setPreco(precoT);
    			E->setNum(numP);
    			E->setArrayProd(*E);
    			
    		}
    
    		cout<<"Deseja adicionar outro produto a sua encomenda? (S/N)";
    		cin>>op;
    		fflush(stdin);
    	}
    }
    view order function:
    Code:
    void mercearia::consultaEncomenda()
    {
    	string i;
    	
    	cout<<"Qual o ID da encomenda que quer ver: ";
    	cin>>i;
    
    	encomendas procura(i);
    
    	set <encomendas>::const_iterator it;
    	
    	it = Enco.find(procura);
    
    	if( it == Enco.end())
    	{
    		cout<<"Nao foi encontrado!\n";
    		exit(1);
    	}
    	else 
    	{
    		cout<<"\nDETALHES \n";
    		cout<<"\tId: "<<it->getIDEnc()<<"\n";
    		cout<<"\tNome: "<<it->getNome()<<"\n";
    		cout<<"\n -- \n" << procura;
    		cout<<"\tPreco Total: "<<it->getPreco()<<"\n";
    		cout<<"\tNum de prod encomendados: "<<it->getNum()<<"\n";
    		system("pause");
    	}
    }
    other constructor's and operator's
    Code:
    mercearia& mercearia::operator += (const encomendas& e)
    {
    	Enco.insert(e);
    	return *this;
    }
    
    void encomendas::setArrayProd(const encomendas &ob)
    {
    	delete[] prod;
    	
    	if (!ob.num){
    		prod = 0;
    		num = 0;
    		return;
    	}
    	prod = new dadosProdEnc[ob.num];
    	if (!prod){
    		prod = 0;
    		num = 0;
    		cout << "\nMemoria insuficiente";
    		return;
    	}
    	num = ob.num;
    	for ( unsigned int i = 0 ; i < num ; i++ )
    		prod[i] = ob.prod[i];
    }
    
    encomendas& encomendas::operator +=(const dadosProdEnc &ob)
    {
    	dadosProdEnc * aux = new dadosProdEnc[num+1];
    	
    	if (!aux)
    	{
    		cout << "\nMemoria insuficiente";
    		return *this;
    	}
    	for ( unsigned int i = 0 ; i < num ; i++ )
    		aux[i] = prod[i];
    	aux[num] = ob;
    
    	num++;
    	delete[] prod;
    	prod = aux;
    	
    	return *this;
    }
    
    string encomendas::getAsString()const
    {
    	ostringstream oss;
    	oss << "\nArray de " << num << " produtos \n";
    	for ( unsigned int i = 0 ; i < num ; i++ )
    		oss << prod[i].getAsString() << endl;
    	return oss.str();
    }
    
    string dadosProdEnc::getAsString()const
    {
    	ostringstream oss;
    	oss << idP << " --------- " << quant ;
    	return oss.str();
    }
    
    ostream & operator<<(ostream & saida, const encomendas & ob)
    {
    	saida << ob.getAsString();
    	return saida;
    }
    after i did these changes i stopped having errors, which is nice, but the problem now is that when i create a order it doesn't get saved :-S
    Last edited by IndioDoido; 11-04-2007 at 03:08 PM.
    "Artificial Intelligence usually beats natural stupidity."

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Your encomendas::operator += looks good.

    >> cout<<"\nInsira a quantidade a encomendar: ";
    Does that line of code run? If it does, then the code looks like it should correctly add the order to E.

    How do you know it doesn't get saved? Is the view order function not showing the order? Or is there other code that displays the contents of the encomendas?

    By the way, I like it better if you don't translate the code. It makes it less likely that there will be typos.

  7. #7
    Registered User IndioDoido's Avatar
    Join Date
    Apr 2007
    Posts
    194
    ok, it's also better for me to leave it in portuguese

    i know that the data isn't being inserted correctly because at first i ran the view order function and it said there weren't any orders.
    when i did a debug with VS2005, and noticed 2 things:

    1st - the data (client name, id order and price) was lost after entering the mercearia& mercearia:perator += (const encomendas& e) or when doing the insertion Enco.insert(e);

    2nd - the data (product id and quantity) was saved into the array, but when i insert another product it won't be saved, in other words, only the first product data is saved in the array.

    i cant seem to understand whats going wrong
    "Artificial Intelligence usually beats natural stupidity."

  8. #8
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Does your encomendas class have a proper copy constructor and copy assignment operator?

    Any time you hold a dynamic array in your class, you need to write three things - a destructor, a copy constructor, and a copy assignment operator=. That's because the default versions created by the compiler won't properly copy or destroy the array.

  9. #9
    Registered User IndioDoido's Avatar
    Join Date
    Apr 2007
    Posts
    194
    humm...

    these are the constructor's and destructor's i'm using:

    Code:
    class dadosProdEnc
    {
    	string idP;
    	unsigned int quant;
    	
    	public:
    		dadosProdEnc()
    		{
    			idP = "i";
    			quant = 0;
    		}
    		dadosProdEnc(string i, unsigned int q)
    		{
    			idP = i;
    			quant = q;
    		}
    
    		string getID() const;
    		void setID(string i);
    		void setQuant(unsigned int q);
    		unsigned int getQuant() const;
    		string getAsString()const;
    	
    };
    ostream & operator<<( ostream & saida, const dadosProdEnc & ob);
    
    class encomendas
    {
    	dadosProdEnc *prod;
    	unsigned int num;
    
    	string idEnc;
    	string nomeComp;
    	unsigned int precoT;
    	
    	public:
    		encomendas()
    		{
    			prod = 0;
    			num = 0;
    		}
    
    		encomendas( const encomendas &ob)
    		{
    			prod = 0;
    			setArrayProd(ob);
    		}
    		~encomendas()
    		{
    			if(prod)
    				delete []prod;
    		}
    		encomendas(string idE)
    		{
    			idEnc = idE;
    		}
    		encomendas(string idE, string nC, unsigned int pT)
    		{
    			idEnc = idE;
    			nomeComp = nC;
    			precoT = pT;
    		}
    
    		void setIDEnc(string idE);
    		string getIDEnc() const;
    		void setNome(string nC);
    		string getNome() const;
    		void setArrayProd(const encomendas &ob);
    
    		encomendas& operator +=(const dadosProdEnc &ob);
    
    		void setNum(unsigned int n);
    		unsigned int getNum() const;
    		void setPreco(unsigned int p);
    		unsigned int getPreco() const;
    
    		string getAsString()const;
    			
    };
    bool operator <(const encomendas &a, const encomendas &b);
    ostream & operator<<(ostream & saida, const encomendas & x);
    What do you mean with a copy constructor? And how do i use a copy assignment operator=?
    "Artificial Intelligence usually beats natural stupidity."

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> encomendas( const encomendas &ob)
    That is the copy constructor. It will work if setArrayProd copies the array from ob correctly (it looks like it does).

    You still need the copy assignment operator. It has the prototype like this:
    Code:
    void operator=(const encomendas &ob);
    It should work like your copy constructor, except that you need to delete the original array first, then copy the new one. The setArrayProd function looks like it already does that, so you're almost there.

  11. #11
    Registered User IndioDoido's Avatar
    Join Date
    Apr 2007
    Posts
    194
    i really hope so

    ok,
    i created this copy assignment operator:
    Code:
    encomendas& encomendas::operator=(const encomendas &ob)
    {
    	if (this != &ob){
    		setArrayProd( ob);
    	}
    	return *this;
    }
    now...where do i use it?
    "Artificial Intelligence usually beats natural stupidity."

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You don't have to use it. If you hold encomendas in a set it will probably be used automatically by the set (which is why I thought that might be the problem).

  13. #13
    Registered User IndioDoido's Avatar
    Join Date
    Apr 2007
    Posts
    194
    ok then, i'm going to try it...

    by the way, does the class dadosProdEnc also need a copy assignment operator?
    "Artificial Intelligence usually beats natural stupidity."

  14. #14
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Not from what I can tell. If all your member variables copy themselves correctly, you don't have to add a copy constructor (or copy assignment operator). In the case of dadosProdEnc, it's only member variables are a string and an unsigned int, which both copy themselves correctly.

    If there are other member variables that you didn't show, then it's possible you would need one. Generally only when you have a destructor that deletes memory will you need copy functions, too (it's called the rule of three).

  15. #15
    Registered User IndioDoido's Avatar
    Join Date
    Apr 2007
    Posts
    194
    Daved i ran the program and it still doesn't save the data.
    But there were improvements.

    I did a debug, and when the program entered the:
    Code:
    mercearia& mercearia::operator += (const encomendas& e)
    {
    	Enco.insert(e);
    	return *this;
    }
    It went only with the data client name, id order and price and the dadosProdEnc data (product id and quantity) didn't enter...in other words it's the opposite of what happened at the begging

    Then i commented E->setArrayProd(*E); from the mercearia::criarEncomenda(encomendas *E) function and know all the data enters the mercearia& mercearia:perator += (const encomendas& e)

    But, even so, it seams that the data isn't saved in the std::set

    I did another debug, and noticed that after inserting Enco.insert(e); the Enco only saved the data product id and quantity, while the data client name, id order and price weren't saved in the std::set.
    Last edited by IndioDoido; 11-04-2007 at 05:19 PM.
    "Artificial Intelligence usually beats natural stupidity."

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array inside an 2dimensional array
    By aserf in forum C Programming
    Replies: 18
    Last Post: 03-22-2008, 06:28 PM
  2. Dynamic 2d array
    By Mithoric in forum C++ Programming
    Replies: 8
    Last Post: 12-29-2003, 09:19 AM
  3. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  4. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM
  5. 2d Array access by other classes
    By deaths_seraphim in forum C++ Programming
    Replies: 1
    Last Post: 10-02-2001, 08:05 AM