Creating a new object within a function implementation for that class.

Just trying to make a new object temporarily for swamping values. It's not liking what I'm doing.

Errors here: http://imgur.com/nE01yZ6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
template<typename T>
void MyVector<T>::swap(MyVector v2)
{
     MyVector<T> *temp = new MyVector<T>;
     for(int i = 0; i < vtr_size; i++)
     {
             temp.push_back(elements[i]);
     }
     
     while(capacity > 0)
     {
             pop_back();
     }

     for(int j = 0; j < v2.size(); j++)
     {
             push_back(v2.elements[j]);
     }
     
     while(v2.capacity > 0)
     {
             v2.pop_back();
     }
     
     for(int k = 0; k < vtr_size; k++)
     {
             v2.push_back(temp.elements[k]);
     }
     
     
     delete temp;   
}
Last edited on
Your first error shows something on line 48. You didn't show that line at all.
Line 48 is
V1.swap(V2);
where V1 and V2 are objects.
Last edited on
Try it this way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<typename T>
void MyVector<T>::swap(MyVector<T> &v2){
    T *temp = new T[v2.vtr_size];
    unsigned temp_size = v2.vtr_size;
    unsigned temp_capacity = v2.capacity;
    for(unsigned i=0; i<v2.vtr_size; ++i)
        temp[i] = v2.elements[i];
    delete [] v2.elements;
    v2.elements = elements;
    v2.vtr_size = vtr_size;
    v2.capacity = capacity;
    elements = temp;
    vtr_size = temp_size;
    capacity = temp_capacity;
}
Topic archived. No new replies allowed.