|
-
May 1st, 2009, 07:47 PM
#1
How to assign an element from a vector to another?
I have two pointers pointing to two different double vectors. Could anybody please let me know the proper way of assigning an element from a vector to the other? Here is a sample code. Please note that even I specify the size of DoubleArray (i.e. DoubleArray *ptr1 = new DoubleArray[3]; ), I still get a bus error. As I am trying to integrate my code to another program written by others, I have to use the pointer to DoubleArray data structure. In their program, they just use DoubleArray *ptr
as far as I can tell. Thanks.
// Assign the third element of the vector pointed to by ptr2 to the second
// element of the vector pointed to by ptr1
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<double> DoubleArray;
int main()
{
DoubleArray *ptr1 = new DoubleArray;
DoubleArray *ptr2 = new DoubleArray;
// Initialize the elements of the first vector (pointed to by ptr1)
(*ptr1)[0] = 10;
(*ptr1)[1] = 20;
(*ptr1)[2] = 30;
// Initialize the elements of the second vector (pointed to by ptr2)
(*ptr2)[0] = 123;
(*ptr2)[1] = 456;
(*ptr2)[2] = 789;
cout << "Second element of the vector pointed to by ptr1: " << (*ptr1)[1] << "\n";
cout << "Third element of the vector pointed to by ptr2: " << (*ptr2)[2] << "\n";
//Assign the third element of the vector pointed to by ptr2 to the second element of the
//vector pointed to by ptr1
(*ptr1)[1] = (*ptr2)[2];
cout << "Modified second element of the vector pointed to by ptr1: " << (*ptr1)[1] << "\n";
delete ptr1;
delete ptr2;
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|