gpt4 book ai didi

c++ - 实现深拷贝

转载 作者:太空宇宙 更新时间:2023-11-04 13:38:37 24 4
gpt4 key购买 nike

我正在尝试在通用指针数组上实现深度复制。我已经和这个问题斗争了 2 天多了,我这辈子都想不通!

我的教授提供了一个相关的测试程序,但我认为这里不需要。至于实现。请参阅下面代码中的选项...

选项 1:flat out 未通过测试,它是一个浅拷贝。

选项 2:产生段错误,我不明白为什么我只是取消引用指针。

选项 3:再次未通过测试。是浅拷贝吗???

选项 4:我什至无法编译,但我希望分配一个新元素并从原始元素中复制这些位。编译器讨厌将指针指向类型而不是类型或其他东西。所以我像在 sizeof(*element) 中那样取消引用它,但它随后说明了一些关于主表达式的内容。

我在这里缺少什么,我明白什么是深拷贝和浅拷贝。您不仅需要复制字段,还需要创建新对象并将新字段指向那些与原始字段具有同等值(value)的对象。

我是否遗漏了一些明显的东西,或者我尝试的逻辑真的有问题吗?我该如何解决?

virtual ConcreteArray<element> *makeDeepCopy() const
{
ConcreteArray* arrayPtr = new ConcreteArray();
int option = 4;
for (size_t index = 0; index < this->size(); ++index)
{
switch (option)
{
case 1:
{
arrayPtr->push_back(*new element);
arrayPtr->at(index) = this->at(index);
break;
}
case 2:
{
arrayPtr->push_back(*new element);
*arrayPtr->at(index) = *this->at(index);
break;
}
case 3:
{
element* E = new element;
*E = this->at(index);
arrayPtr->push_back(*E);
break;
}
case 4:
{
arrayPtr->push_back(*new element);
memcpy(this->at(index), arrayPtr->back(), sizeof(element));
}
default: return nullptr;
}
}
return arrayPtr;
}

有关更多信息,请参阅构造函数...

template<class element>
class ConcreteArray : public Array<element>
{
private:
/// Default capacity is an arbitrary small value > 0
static const size_t defaultCapacity = 8;

element *m_Data; /// Pointer to storage for elements
size_t m_Size; /// Number of elements stored
size_t m_Capacity; /// Number of elements that can be

public:

////////////////////////////////////////////////////////
/// Default constructor
ConcreteArray() :
m_Size(0),
m_Capacity(ConcreteArray::defaultCapacity)
{
m_Data = new element[m_Capacity];
};

////////////////////////////////////////////////////////
/// Copy Constructor (shallow copy)
ConcreteArray(const ConcreteArray<element> &original) :
m_Size(original.m_Size),
m_Capacity(original.m_Capacity)
{
assert(m_Size <= m_Capacity);

m_Data = new element[m_Capacity];
for(size_t i = 0; i < m_Size; i++)
{
m_Data[i] = original.m_Data[i];
}
};

还有我调用的函数,不包括 memcpy()...

   ////////////////////////////////////////////////////////
/// Returns the number of elements in array
virtual size_t size() const
{
return m_Size;
};

////////////////////////////////////////////////////////
/// Append element at end of array expanding storage for
/// array as necessary
void push_back(element const &anElement)
{
this->insertAt(anElement, this->size());
};

////////////////////////////////////////////////////////
/// The array is extended by inserting element before
/// the element at the specified index increasing the
/// array size by 1.
/// Any existing elements at index and beyond are moved
/// to make space for the inserted element.
/// If index is equal to size(), element is appended to
/// the end of the array.
/// Array storage expands as necessary.
virtual void insertAt(element const &anElement,
size_t index)
{
assert(index <= m_Size);

if(m_Size == (m_Capacity - 1))
{ // Double the amount of memory allocated for
// storing elements
m_Capacity *= 2;
element *newData = new element[m_Capacity];
for(size_t i = 0; i < m_Size; i++)
{
newData[i] = m_Data[i];
}
delete [] m_Data;
m_Data = newData;
}

assert((m_Size + 1) < m_Capacity);

if(index < m_Size)
{ // Move elements after index to make room for
// element to be inserted
for(size_t i = m_Size - 1; i > index; i--)
{
m_Data[i] = m_Data[i-1];
}
}

m_Size++;
m_Data[index] = anElement;
};

////////////////////////////////////////////////////////
/// Returns the element at index
virtual element const &at(size_t index) const
{
assert(index < m_Size);

return m_Data[index];
};

////////////////////////////////////////////////////////
/// Returns the element at index
virtual element &at(size_t index)
{
assert(index < m_Size);

return m_Data[index];
};

基本模板类...

//
// Array.h
// Project1
//

#ifndef __Array__Array
#define __Array__Array

#include <stdlib.h> // For size_t
#include <iostream> // std::cout
#include <iterator> // std::iterator, std::input_iterator_tag
#include <sstream>
#include <string>

///////////////////////////////////////////////////////////
/// This class encapsulates an array storing any number of
/// elements limited only by the amount of memory available
/// in the host process and provides access to stored
/// elements via within the array.
template<typename element>
class Array
{
public:
///
/// Virtual Destructor
virtual ~Array() {};

///////////////////////////////////////////////////////////
/// BEGIN Pure virtual member functions to be implemented
/// by concrete subclasses
///////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
/// These member functions each return an iterator to
/// the first element in the array.
virtual element * begin() = 0;
virtual const element * begin() const = 0;

////////////////////////////////////////////////////////
/// These member functions each return an iterator to
/// one index past the end of the array.
virtual element * end() = 0;
virtual const element * end() const = 0;

////////////////////////////////////////////////////////
/// The array is extended by inserting anElement before
/// the element at the specified index increasing the
/// array size by 1. Any existing elements at index
/// and beyond are moved to make space for the inserted
/// element.
/// If index is equal to size(), anElement is appended to
/// the end of the array. Array storage expands as
/// necessary.
virtual void insertAt(element const &anElement,
size_t index) = 0;

////////////////////////////////////////////////////////
/// Remove element at index from array moving all
/// elements after index down one position to fill gap
/// created by removing the element reducing the array
/// size by 1
virtual void removeAt(size_t index) = 0;

////////////////////////////////////////////////////////
/// Returns the number of elements in array
virtual size_t size() const = 0;

////////////////////////////////////////////////////////
/// Sets the element value stored at the specified
/// index. works as long index is less than size().
virtual void setAt(element const &anElement,
size_t index) = 0;

////////////////////////////////////////////////////////
/// Returns a reference to the element at index
virtual element const &at(size_t index) const = 0;

////////////////////////////////////////////////////////
/// Returns a reference to the element at index
virtual element &at(size_t index) = 0;

///////////////////////////////////////////////////////////
/// END Pure virtual member functions to be implemented
/// by concrete
///////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
/// Remove all elements from array and set array's size
/// to 0
void clear()
{
while(0 < this->size())
{
this->pop_back();
}
};

element &back()
{
return at(size() - 1);
}

element const &back() const
{
return at(size() - 1);
}

////////////////////////////////////////////////////////
/// Append element at end of array expanding storage for
/// array as necessary
void push_back(element const &anElement)
{
this->insertAt(anElement, this->size());
};

////////////////////////////////////////////////////////
/// Removes and returns the last element in array
void pop_back()
{
assert(0 < this->size());

this->removeAt(this->size() - 1);
};

////////////////////////////////////////////////////////
/// Appends all elements in a Array to array expanding
/// storage for array as necessary
void append(Array &source)
{
const size_t count = source.size();

for(size_t i = 0; i < count; i++)
{
this->push_back(source.at(i));
}
};

////////////////////////////////////////////////////////
/// Returns a reference to the element at index. This
/// operator enables semantics similar to built-in
/// arrays. e.g.
/// someArray[5] = someArray[6];
element &operator [](size_t index)
{
return this->at(index);
}

////////////////////////////////////////////////////////
/// Returns a reference to the element at index. This
/// operator enables semantics similar to built-in
/// arrays. e.g.
/// someArray[6];
element const &operator [](size_t index) const
{
return this->at(index);
}

////////////////////////////////////////////////////////
/// Returns a string representation of the array's
/// elements
operator std::string() const
{
std::ostringstream tempOStream;

tempOStream << "(";
std::copy(begin(), end(),
std::ostream_iterator<void *>(tempOStream, ", "));
tempOStream << ")\n";

return tempOStream.str();
}
};

#endif /* defined(__Arrayy__Array__) */

还有扩展类

//
// ConcreteArray.h
// Project1
//
//

#ifndef __Array__ConcreteArray__
#define __Array__ConcreteArray__

#include "Array.h"
#include <string.h> // For memmove()
#include <stdlib.h> // For calloc(), realloc()
#include <algorithm>
#include <assert.h>
#include <iterator> // std::iterator, std::input_iterator_tag

///////////////////////////////////////////////////////////
/// BEGIN code added for Project 3
///////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
// THIS FUNCTION MUST BE DECLARED BEFORE
// ConcreteArray OR ELSE COMPILER WILL NOT KNOW HOW
// TO COPY elements.
////////////////////////////////////////////////////////
template<typename T>
T *deepCopy(T *original)
{
return original->makeDeepCopy();
}


////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
// THIS FUNCTION MUST BE DECLARED BEFORE
// ConcreteArray OR ELSE COMPILER WILL NOT KNOW HOW
// TO COPY long *.
////////////////////////////////////////////////////////
long *deepCopy(long *original)
{
return new long(*original);
}

///////////////////////////////////////////////////////////
/// END code added for Project 3 (SEE THE
/// Project 3 "To Do" CODE BELOW
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
/// This class encapsulates an array storing any number of
/// elements limited only by the amount of memory available
/// in the host process and provides access to stored
/// elements via index position within the array.
template<class element>
class ConcreteArray : public Array<element>
{
private:
/// Default capacity is an arbitrary small value > 0
static const size_t defaultCapacity = 8;

element *m_Data; /// Pointer to storage for elements
size_t m_Size; /// Number of elements stored
size_t m_Capacity; /// Number of elements that can be

public:

////////////////////////////////////////////////////////
/// Default constructor
ConcreteArray() :
m_Size(0),
m_Capacity(ConcreteArray::defaultCapacity)
{
m_Data = new element[m_Capacity];
};

////////////////////////////////////////////////////////
/// Copy Constructor (shallow copy)
ConcreteArray(const ConcreteArray<element> &original) :
m_Size(original.m_Size),
m_Capacity(original.m_Capacity)
{
assert(m_Size <= m_Capacity);

m_Data = new element[m_Capacity];
for(size_t i = 0; i < m_Size; i++)
{
m_Data[i] = original.m_Data[i];
}
};

////////////////////////////////////////////////////////
/// Destructor
virtual ~ConcreteArray()
{
delete [] m_Data;
m_Size = 0;
};

////////////////////////////////////////////////////////
/// The array is extended by inserting element before
/// the element at the specified index increasing the
/// array size by 1.
/// Any existing elements at index and beyond are moved
/// to make space for the inserted element.
/// If index is equal to size(), element is appended to
/// the end of the array.
/// Array storage expands as necessary.
virtual void insertAt(element const &anElement,
size_t index)
{
assert(index <= m_Size);

if(m_Size == (m_Capacity - 1))
{ // Double the amount of memory allocated for
// storing elements
m_Capacity *= 2;
element *newData = new element[m_Capacity];
for(size_t i = 0; i < m_Size; i++)
{
newData[i] = m_Data[i];
}
delete [] m_Data;
m_Data = newData;
}

assert((m_Size + 1) < m_Capacity);

if(index < m_Size)
{ // Move elements after index to make room for
// element to be inserted
for(size_t i = m_Size - 1; i > index; i--)
{
m_Data[i] = m_Data[i-1];
}
}

m_Size++;
m_Data[index] = anElement;
};

////////////////////////////////////////////////////////
/// Remove element at index from array moving all
/// elements after index one position to fill gap
/// created by removing the element
virtual void removeAt(size_t index)
{
assert(index < m_Size);

if((index + 1) < m_Size)
{ // Move elements to close gap left by removing
// an element
for(size_t i = index + 1; i < m_Size; i++)
{
m_Data[i-1] = m_Data[i];
}
}
m_Size--;
};

////////////////////////////////////////////////////////
/// Returns the number of elements in array
virtual size_t size() const
{
return m_Size;
};

////////////////////////////////////////////////////////
/// Sets the element value stored at the specified
/// index. works as long index is less than size().
virtual void setAt(element const &anElement,
size_t index)
{
assert(index < m_Size);

m_Data[index] = anElement;
};

////////////////////////////////////////////////////////
/// Returns the element at index
virtual element const &at(size_t index) const
{
assert(index < m_Size);

return m_Data[index];
};

////////////////////////////////////////////////////////
/// Returns the element at index
virtual element &at(size_t index)
{
assert(index < m_Size);

return m_Data[index];
};



///////////////////////////////////////////////////////////
/// BEGIN code added for Project 3
///////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// Constructor via iterators (shallow copy)
template <class _InputIterator>
ConcreteArray(
_InputIterator start,
_InputIterator end) :
m_Size(0),
m_Capacity(ConcreteArray::defaultCapacity)
{
m_Data = new element[m_Capacity];

for(_InputIterator it(start); it != end; ++it)
{
this->push_back(*it);
}
}

////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// Returns a newly allocated array produced by deep
/// copying this.
virtual ConcreteArray<element> *makeDeepCopy() const
{
//////////////////////////////////////
/// ***** TO DO *****
/// Implement deep copy logic here!
//////////////////////////////////////
ConcreteArray* arrayPtr = new ConcreteArray();
int option = 5;
for (size_t index = 0; index < this->size(); ++index)
{
switch (option)
{
case 1:
{
arrayPtr->push_back(*new element);
arrayPtr->at(index) = this->at(index);
break;
}
case 2:
{
arrayPtr->push_back(*new element);
*arrayPtr->at(index) = *this->at(index);
break;
}
case 3:
{
element* E = new element;
*E = this->at(index);
arrayPtr->push_back(*E);
break;
}
case 4:
{
arrayPtr->push_back(*new element);
//memcpy(this->at(index), arrayPtr->back(), sizeof(element));
}
case 5:
{
element* aNewElementPtr = new element;
element origElementPtr = at(index);
*aNewElementPtr = origElementPtr;
}
default: return nullptr;
}
}
return arrayPtr;
}

////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// These member functions each return an iterator to
/// the first element in the array.
virtual element * begin()
{
//return nullptr; // Replace this line
return m_Data;
};

////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
virtual const element * begin() const
{
//return nullptr; // Replace this line
return m_Data;
};

////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// These member functions each return an iterator to
/// one index past the end of the array.
virtual element * end()
{
//return nullptr; // Replace this line
return m_Data + m_Size;
};

////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
virtual const element * end() const
{
//return nullptr; // Replace this line
return m_Data + m_Size;
};

////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// Overloaded assignment operator
ConcreteArray &operator=(
const ConcreteArray &original)
{
if (this != &original) // protect against invalid self-assignment
{
//////////////////////////////////////
/// ***** TO DO *****
/// Implement deep copy logic here!
//////////////////////////////////////
return *original.makeDeepCopy();
}
return *this;
}
};


////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////
template<typename T>
ConcreteArray<T> *deepCopy(ConcreteArray<T> *original)
{
return original->makeDeepCopy();
}

#endif /* defined(__Array__ConcreteArray__) */

最佳答案

创建一个与原始缓冲区大小相同的新数组。

依次对每一对对应的元素调用lhs_element = deepCopy(rhs_element),其中lhs_element为新数组中的元素,rhs_element为原数组中的元素。

关于c++ - 实现深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28653526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com