So I am trying to make a copy of a vector that would be immediate instead of copying one by one the values of a vector to the other vector.
The code that I have created to test it is:
#include <iostream>
#include <vector>
int main(){
std::vector<float> initial_vector(5, 0.0);
std::vector<float> final_vector(5, 1.0);
std::cout << "Initially, the vector has the following values: " << std::endl;
for (auto val: initial_vector){
std::cout << "\t ." << val << std::endl;
}
std::cout << "The final vector should have the following values: " << std::endl;
for (auto val: final_vector){
std::cout << "\t ." << val << std::endl;
}
initial_vector = final_vector;
std::cout << "The final vector has the following values: " << std::endl;
for (auto val: initial_vector){
std::cout << "\t ." << val << std::endl;
}
std::cout << "Initial vector is: " << initial_vector << std::endl;
return 0;
}
What I encounter is that the vector actually copies the values. The vector "initial_vector" ends up having the values of the "final_vector". I suspected then that the vector (as a container of an array that is), is acting as a pointer when declaring everything this way. The problem appears when I try to print the variable "initial_vector" to check if is a pointer, and it gives the error "error: no type named ‘type’ in ‘struct std::enable_if<false, void>’".
Also, I was wondering if, having a method of a class that receives the pointer of the vector as an input to update the contents of an inner vector, would it be required to free the memory of any of the vectors?
CodePudding user response:
If you need to have multiple copies to point to same internal data without using std::span, then encapsulate the vector with a smart pointer to the vector to be shared:
#include <vector>
#include <iostream>
#include <memory>
struct OriginalVector
{
std::shared_ptr<std::vector<int>> vec;
OriginalVector(){ vec = std::make_shared<std::vector<int>>(); }
void push_back(int elm){ vec->push_back(elm); }
int & operator[](int idx){ return vec->operator[](idx);}
};
int main() {
OriginalVector ov;
ov.push_back(5);
OriginalVector stillOriginal = ov;
std::cout<<ov[0]<<std::endl;
std::cout<<stillOriginal[0]<<std::endl;
stillOriginal[0]=100;
std::cout<<ov[0]<<std::endl;
return 0;
}
output:
5
5
100
also a vector of smart-pointers work but its still O(N) to initialize from original vector due to N number of smart pointer assignments. Pointer to vector is O(1) to assign.
CodePudding user response:
No, std::vector is not acting as a pointer, vector is the templatized class it has an overloaded assignment operator in it, that you are calling with initial_vector = final_vector;
You are getting the error "error: no type named ‘type’ in ‘struct std::enable_if<false, void>’". when printing "initial_vector" variable because you are printing a class object to do that you need to overload "<<" operator in vector class.
