0

I have a vector and I need to copy it as a template vector class? So if I modify one element in the original vector it needs to change in the other too. Here is my main function

#include <iostream>
#include "thisheader.h"
#include <vector>

int main()
{
    std::vector<int> v;
    v.push_back(2);
    v.push_back(4);
    v.push_back(6);
    
    std::vector<double> a;
    a.push_back(4.32);    
    templatevectorclass<int> vv(v);
    templatevectorclass<double> av(a);

    v[0] = 3;
    if(vv[0]==v[0]){
        std::cout << "good" ;
    }else{
        std::cout << "bad";
    }

    a[0] = 2.4;
    if(av[0]==a[0]){
        std::cout << "good" ;
    }else{
        std::cout << "bad";
    }
}

Here is the class that needs to copy the vector by reference:

#include <vector>    
template<class T1>
class templatevectorclass {
    std::vector<T1> copy;
    T1* array;

public:    
    templatevectorclass(std::vector<T1> vector) {
        for(int i = 0; i < vector.size(); i++)
        {
            copy.push_back(vector[i]);

        }
    }
  
    T1 const& operator[](int index) const
    {
        return copy[index];
    }
};
  • 1
    Sorry, I don't get your question. Could you rephrase it? – 273K May 23 '21 at 19:22
  • I only see you don't need the loop. Just copy = vector. – 273K May 23 '21 at 19:23
  • Yes, I want to copy the vector to a template class using reference, so if I change the value the original vector, the template class vector reference should change as well. Idk how to use references , could you help me? – OrangeLover25 May 23 '21 at 19:24
  • Could you provide me a code? I don't know how to copy the vector with reference? Thanks :D – OrangeLover25 May 23 '21 at 19:26
  • 2
    Please define what is "copy by reference"? Copy is one thing, reference is another thing. The reference can't be a copy. – 273K May 23 '21 at 19:26
  • Does this answer your question? [Reference as class member initialization](https://stackoverflow.com/questions/8285040/reference-as-class-member-initialization) – 273K May 23 '21 at 19:36
  • "So if I modify one element in the original vector it needs to change in the other too" Are you sure that you don't just need a *reference* of the original vector (whitout any copy)? – Bob__ May 23 '21 at 20:25

1 Answers1

0

As I understand, you would like to store reference inside templatevectorclass

template<class T1>
class templatevectorclass {
    std::vector<T1> &reference;

public:    
    templatevectorclass(std::vector<T1> &vector) : reference(vector) {
    }
  
    T1 const& operator[](int index) const
    {
        return reference[index];
    }
};