vector of structs

O

oceanx

Hi everybody,

the "insert" function of a vector copies the param? or just refers to
the structure?

for example:

typedef struct {
int a;
...
} structType;

void f ( vector <structType> & v){
stryctType xx;
xx.a = 10;
v.add (xx); // it really *copies* xx in v... isn't it?
}

int main(){

f (vect);
cout << vect[0].a;
}


it works, but... is it correct?

thanks,
Major
 
C

Chris Theis

Hi everybody,

the "insert" function of a vector copies the param? or just refers to
the structure?

for example:

typedef struct {
int a;
...
} structType;

void f ( vector <structType> & v){
stryctType xx;
xx.a = 10;
v.add (xx); // it really *copies* xx in v... isn't it?
}

int main(){

f (vect);
cout << vect[0].a;
}


it works, but... is it correct?

Sorry, but the program above neither works/compiles nor is it correct. Among
other things there is no member function add for the class vector, so I
guess you meant something like insert or push_back. These functions do
create a copy which is placed in the container and thus, there is the
requirement that those objects stored in a standard container must be copy
constructible.

HTH
Chris
 
M

Mateusz Loskot

Hi everybody,

the "insert" function of a vector copies the param? or just refers to
the structure?

Copy of structure will be inserted.
I'd recommend you to read this great book by Nicolai M. Josuttis:
http://www.josuttis.com/libbook/index.html

Recommended chapter with explanation is 6.1 "Common Container Abilities
and Operations".

Shortly, ALL STL containers are based on semantic of value not
reference, so they operate on copies internally.
 
O

oceanx

Mateusz said:
Copy of structure will be inserted. [cut]
Shortly, ALL STL containers are based on semantic of value not
reference, so they operate on copies internally.

cheers!
I have "Borland C++: The Complete Reference" by Schildt, but it isn't
really clear on this point...
 
O

oceanx

Chris said:
Sorry, but the program above neither works/compiles nor is it correct. Among
other things there is no member function add for the class vector, so I
guess you meant something like insert or push_back. These functions do
create a copy which is placed in the container and thus, there is the
requirement that those objects stored in a standard container must be copy
constructible.

sorry, my fault (yes, I meant something like insert or push_back)...
when I wrote I was far from my compiler :-(

thanks a lot,

Major
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top