473,769 Members | 6,583 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem inserting into Vector

Hi,I had a problem while I was doing the assignment .the code is like
below(not exact):
//=============== =============== ========

class Buyer
{
private:
int _product;

public:
//Buyer(void){ _product=-1;);
int get_product(voi d);
Buyer( int n ){ _product = n;};
};

int Buyer::get_prod uct(void){
return _product;
};

std::vector<Buy er *> buyer_queue;

int main( int argc, char *argv[] )
{
for(;;){
int i=int(1+rand()% 10);
Buyer b=Buyer(i);

buyer_queue.pus h_back(&b);
printf("\nB[%d]",(*buyer_q ueue[buyer_queue.siz e()-1]).get_product() );

for (int j=0;j<buyer_que ue.size();j++){
printf("\t\n looped [%d]",(*buyer_q ueue[j]).get_product() );

}
usleep(1000000) ;
}
}

//=============== =============== ======
the problem is in the for loop,why it outputs the same value for
member"product" of each Buyer?
Jul 22 '05 #1
7 1560
wu*******@hotma il.com wrote:
Hi,I had a problem while I was doing the assignment .the code is like
below(not exact):
//=============== =============== ========

class Buyer
{
private:
int _product;

public:
//Buyer(void){ _product=-1;);
int get_product(voi d);
Buyer( int n ){ _product = n;};
};

int Buyer::get_prod uct(void){
return _product;
};

std::vector<Buy er *> buyer_queue;

int main( int argc, char *argv[] )
{
for(;;){
int i=int(1+rand()% 10);
Buyer b=Buyer(i);

buyer_queue.pus h_back(&b);
printf("\nB[%d]",(*buyer_q ueue[buyer_queue.siz e()-1]).get_product() );

for (int j=0;j<buyer_que ue.size();j++){
printf("\t\n looped [%d]",(*buyer_q ueue[j]).get_product() );

}
usleep(1000000) ;
}
}

//=============== =============== ======
the problem is in the for loop,why it outputs the same value for
member"product" of each Buyer?


Don't see any of the "Miranda" functions.

Provide a default constructor, copy constructor, and assignment operator.

Also, you want to call srand() before you call rand().
Jul 22 '05 #2
> Buyer b=Buyer(i);

buyer_queue.pus h_back(&b);


The address you are storing is the address of a local variable with automatic
storage duration. That variable is being destroyed at the end of the for loop
in which it is declared and thusly your vector contains a pointer to an object
that has been destroyed.

However, in my runtime environment every pass through the loop results in that
variable being reconstructed at the same memory location as the last pass
through the loop. As a result all the pointers stored in the vector point to
the same object and at the time those pointers are accessed they are infact
pointing to a valid object.

Is there some reason you just didn't use std::vector<Buy er>?


Jul 22 '05 #3
DaKoadMunky wrote:
Buyer b=Buyer(i);

buyer_queue.pus h_back(&b);

The address you are storing is the address of a local variable with automatic
storage duration. That variable is being destroyed at the end of the for loop
in which it is declared and thusly your vector contains a pointer to an object
that has been destroyed.

However, in my runtime environment every pass through the loop results in that
variable being reconstructed at the same memory location as the last pass
through the loop. As a result all the pointers stored in the vector point to
the same object and at the time those pointers are accessed they are infact
pointing to a valid object.

Is there some reason you just didn't use std::vector<Buy er>?



declare buyer as a gloabl variable would do ?if I want to insert many
buyers with random product.
Jul 22 '05 #4
>declare buyer as a gloabl variable would do ?if I want to insert many
buyers with random product.


The object passed to vector<T>::push _back will be copied using the T copy
constructor. It is the copy that becomes part of the controlled sequence.

vector<Buyer> buyers;

for(int i=0;i<10;++i)
{
Buyer buyer(i);
buyers.push_bac k(buyer);
}

At this point the vector contains 10 elements that are copies of the elements
that were arguments to vector<T>::push _back.

Jul 22 '05 #5
In message <OC************ *@newssvr14.new s.prodigy.com>, red floyd
<no*****@here.d ude> writes
wu*******@hotm ail.com wrote:
Hi,I had a problem while I was doing the assignment .the code is like
below(not exact):
//=============== =============== ========
class Buyer
{
private:
int _product;
public:
//Buyer(void){ _product=-1;);
int get_product(voi d);
Buyer( int n ){ _product = n;};
};
int Buyer::get_prod uct(void){
return _product;
};
std::vector<Buy er *> buyer_queue;
int main( int argc, char *argv[] )
{
for(;;){
int i=int(1+rand()% 10);
Buyer b=Buyer(i);
buyer_queue.pus h_back(&b);
printf("\nB[%d]",(*buyer_q ueue[buyer_queue.siz e()-1]).get_product() );
for (int j=0;j<buyer_que ue.size();j++){
printf("\t\n looped [%d]",(*buyer_q ueue[j]).get_product() );

}
usleep(1000000) ;
}
}
//=============== =============== ======
the problem is in the for loop,why it outputs the same value for
member"produc t" of each Buyer?
Don't see any of the "Miranda" functions.

Provide a default constructor, copy constructor, and assignment operator.


Why? The class doesn't use pointers or manage resources, so the
compiler-generated copy and assignment will have the correct semantics.
Writing your own, unnecessarily, is just another opportunity to add
errors.
Also, you want to call srand() before you call rand().


The real problem is that every entry in the vector is a pointer to
(effectively) the *same* object, 'b'. So no matter which element of the
vector you look at, you see the last value assigned to b.

--
Richard Herring
Jul 22 '05 #6

<wu*******@hotm ail.com> wrote in message
news:10******** *******@clint.i ts.waikato.ac.n z...
DaKoadMunky wrote:
Buyer b=Buyer(i);

buyer_queue.pus h_back(&b);

The address you are storing is the address of a local variable with automatic storage duration. That variable is being destroyed at the end of the for loop in which it is declared and thusly your vector contains a pointer to an object that has been destroyed.

However, in my runtime environment every pass through the loop results in that variable being reconstructed at the same memory location as the last pass through the loop. As a result all the pointers stored in the vector point to the same object and at the time those pointers are accessed they are infact pointing to a valid object.

Is there some reason you just didn't use std::vector<Buy er>?


declare buyer as a gloabl variable would do ?if I want to insert many
buyers with random product.


No. Simply store Buyer objects instead of pointers to them. Then each
object in the vector will be unique, because push_back will make a copy of
the object and store that. Then when you re-use the object, it will be
different.

Also, you should use

Buyer b(i);

instead of

Buyer b=Buyer(i);

There's no need for the assignment. (Perhaps you were thinking of "Buyer* b
= new Buyer(i);"?)

-Howard

Jul 22 '05 #7
Richard Herring wrote:
[ reply to my incredibly dumb comment redacted]


You're right... I missed the fact that he was storing *pointers*. I've
been bitten by bad or missing Miranda functions with vectors before, so
that's why I suggested that.
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2415
by: Dave | last post by:
I'm crossposting this to both comp.lang.c++ and gnu.gcc because I'm not sure if this is correct behavior or not, and I'm using the gcc STL and compiler. When calling vector<int>::push_back(0), an iterator that I've set in a loop gets changed. Here's an example of the problem (sorry about the lack of indentation, posting this from Google): #include <vector> #include <iostream>
3
2237
by: KL | last post by:
Well, I am back. This time our assignment has us filling a vector and then timing how long it takes to find a spot in the vector to insert a new item, and the time required to insert the item after that spot is found. Well, I am kinda lost on this finding things in a vector. I mean, wouldn't you just go to vector, and then ....well then I gotta find out how to do an insert in a vector. Does this involve changing the pointer to point...
0
2607
by: rokuingh | last post by:
ok, so i've been working on this one for quite a while, and the code is very big so i'm just going to give the relevant parts. this is a program that builds polymers (chemical structures of repeated monomers) which are represented as doubly pointed noncomplete binary trees. There are three different types of monomers (hence the three different constructer calling functions) the first one is the "leaves" of the tree, the second adds length...
4
5555
by: Prasad | last post by:
HI. I have written the following code..in VC++(win32 console with MFC support) CMapStringToPtr chat; vector<UserMessage *> v; /* UserMessage is a class.. */
12
3522
by: Marcus Kwok | last post by:
I am not sure if this is something that is covered by the Standard, or if it's an implementation detail of my Standard Library. I am reading in a large amount of data into a std::set. There is an overload for std::set::insert() that takes in an iterator as a hint as to where the new value should be inserted, and my implementation (Dinkumware) says that if the hint is good (meaning the iterator points immediately before or after where...
12
4915
by: desktop | last post by:
Why does insert only work when specifying an iterator plus the object to be inserted: std::vector<intt; std::vector<int>::iterator it; it = t.begin(); t.insert(it,33); If I use push_back instead I don't need to supply the iterator. But what
1
1451
by: jesmi | last post by:
hi i got problem in inserting the date into the database. my requirement is that when i choose a date ie from :2007-01-01 & to :2007-12-01 then all the dates starting from 2007-02-01 upto 2007-12-01 should be inserted. while inserting year,month and day should be incremented.i tried a lot and my code only increments the month. Following is my code: public void save(String eventDt,String toDt) throws Exception{ Connection con =...
10
2206
by: oktayarslan | last post by:
Hi all; I have a problem when inserting an element to a vector. All I want is reading some data from a file and putting them into a vector. But the program is crashing after pushing a data which has string value. I really do not understand why push_back() function is trying to remove previously inserted data. Thanks for any help
4
1472
by: alexjcollins | last post by:
The following program demonstrates the problem: #include <vector> #include <iostream> #include <tvmet/Vector.h> typedef tvmet::Vector<double, 3Vector3d; class Mesh {
0
9590
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10051
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9866
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3968
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3571
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.