Here is something that I've done in Java, but I am having difficulty figuring it out in C++.
Basically, I have two arrays, and I would like to copy the contents of the second array into the first array. Instead of wasting time in a loop that copies the contents of each array element one at a time from the second array to the first, I would just like my first array variable to point to the location where the second array is stored.
Here is an example:
void modify(int[]);
int main (){
// foo points to (for example) memory location 123
int foo[5] = { 16, 2, 77, 40, 12071 };
modify(foo);
// foo now contains the modified data
return 0;
}
void modify(int bar[]){
// bar points to memory location 123
// (ie, bar points to the same location as foo)
// baz points to (for example) memory location 4567
int baz[5];
// this loop can't modify my data in-place,
// so it uses baz temporarily
for(int i = 0; i < 5; i++){
int j;
if(i == 0) j = 4;
else j = i - 1;
baz[i] = bar[i] + bar[j];
}
// baz now contains the modified data
// now, I would like to put the data located in 4567 (baz) into foo
// I know I could loop through each element one at a time like:
// for(int i; i < 5; i++)
// bar[i] = baz[i];
// but I feel that for large arrays, this could be unnecessarily slow
// it would be more efficient to say:
// "ok, now foo points to memory location 4567"
// but I don't know how to say that in C++
bar = baz; // this doesn't work :-(
foo = baz; // neither does this :'(
}
How would I do this in C++?
-- Brian
std::vectorinstead of C-style arrays. The=operator will work then. You'll also be able efficiently swap the contents of two vectors.std::copy(),std::vector<int>respectively.