问题
A simple thing as I thought at first seems to be harder than I thought. I want to copy a vector of vectors of type int inside a copy constructor.
std::vector<std::vector<int> * > * bar;
I tried this but it is not working:
Foo(const Foo& rhs)
: bar(new std::vector<std::vector<int> * >(rhs.vec->size())) {
for (std::size_t i = 0; i < rhs.bar->size(); i++) {
bar->push_back(new std::vector<int>());
for (size_t j = 0; j < (*rhs.bar)[i]->size(); j++) {
bar->back()->push_back((*rhs.bar)[i]->at(j));
}
}
}
I also thought if I could use something with swap
and back()
but I am not sure if this is working out.
Could somebody show me a proper way to make a copy? Thanks for your help in advance!
回答1:
Since your actual storage type is int
, I can think of no good reason to use any pointers in this case. Change your member variable to not use pointers, and simply let the copy constructors of the vector
objects do the work for you.
class T
{
public:
T() {};
// For this class, the copy constructor isn't even necessary!
private:
std::vector<std::vector<int>> v_;
};
回答2:
If you have what you said, a vector of vectors of ints, and not what you showed (a pointer to a vector of pointers to vectors to ints), then the object can do it already. You just use its copy constructor or assignment operator:
std::vector<std::vector<int> > vec;
std::vector<std::vector<int> > copy_of_vec = vec;
Yes, it's really that simple once you get rid of all the pointers.
来源:https://stackoverflow.com/questions/16155054/copy-vector-of-vectors-in-copy-constructor