Re: How to copy vector?
On Jan 26, 7:00 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
Immortal Nephi wrote:
I create two vector variables. First variable: data is initia=
lized
with integers. Second variable: copyData is empty. Both have same
sizes.
It is customary to describe what *type* your variables have. 'vector'
(or, rather, 'std::vector') is a template, which has to be instantiated
with a type (at least).
How do I write correct code to copy all elements from data to
copyData?
How do you copy a 'double'? You assign it. What about a 'bool'? =
You
assign it. Why do you think it's different with 'std::vector'? It's
not. You simply assign it.
> I don't have to go through iterator loop to copy each
element.
No, you don't.
I want to know that vector data should be auto storage in the gl=
obal
function's stack frame.
Huh?
> Then, the return type will be vector to copy
all elements.
If result size is different and is more than 100 elements, will
copyData be automatically resized?
Uh... Assignment takes care of everything, if that's what you're askin=
g.
vector< int > foo()
{
int numData = 1;
vector< int > result;
result.resize( 100 );
for( vector< int >::iterator it = result.begin();
it != result.end(); ++it )
*it = numData++;
return result;
}
Looks good. Or, you could simply do
int numData = 1;
vector<int> result;
for (int i = 0; i < 100; i++)
result.push_back(numData++);
(or drop 'numData' altogether and push 'i').
int main()
{
vector< int > copyData;
copyData.resize( 100 );
No need to resize.
copyData = foo();
That's just fine. Or, you could simply initialise it with the return
value of 'foo()':
vector<int> copyData = foo();
return 0;
}
Victor,
Thank you for your assistance. I have another question. First
variable has 640 elements. Second variable has only 64 elements.
They look like ten 2D images with 64 area of elements.
I can't use assignment to copy one out of ten images. Do I need to
use memory address with offset? Or I have to use three dimension
array?
vector< int > foo()
{
static const int TwoDimensionArray = 10;
static const int Width = 8;
static const int Height = 8;
vector< int > result;
result.resize( TwoDimensionArray * Width * Height );
// or vector< int > result[ TwoDimensionArray ][ Width ][ Height ];
for( int i = 0; i != result.size(); ++i )
result.push_back( i );
return result; // I want to copy only one image with 64 elements with
memory address
// or return result[5][0][0];
}