-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
10.6 컨테이너 클래스 숙제 피드백
23.02.04 20:23 작성 조회수 147
0
안녕하세요 강의를 듣고있는 학생입니다.
10.6에서 컨테이너 클래스의 개념을 설명해주시고
IntArray를 직접 구현해보는 숙제를 내주셔서 직접 머리를 짜내서 코드를 구현해봤습니다.
이 글을 보신 숙련자 분들께 제가 구현한 intArray를 피드백 받고싶어서 글을 작성합니다.
#include <iostream>
#include <vector>
using namespace std;
class IntArray
{
private:
int m_length = 0;
int* m_data = nullptr;
public:
IntArray(const int length)
:m_length(length)
{
m_data = new int[m_length];
}
IntArray(const std::initializer_list<int>& list)
:IntArray(list.size())
{
int count = 0;
for (auto& ele : list)
{
//cout << "list" << endl;
m_data[count] = ele;
count++;
}
}
~IntArray()
{
delete[] m_data;
}
void initialize(const std::initializer_list<int>& list)
{
delete[] m_data;
m_length = list.size();
m_data = new int[m_length];
if (m_data != nullptr)
{
int count = 0;
for (auto& ele : list)
{
m_data[count] = ele;
count++;
}
}
}
void reset()
{
delete[] m_data;
m_data = nullptr;
}
void resize(const int size)
{
m_length = size;
}
void insertBefore(const int & value, const int & ix)
{
m_length += 1;
int *n_data = new int[m_length];
int i = ix;
for (int n = 0; n < ix; n++)
n_data[n] = m_data[n];
n_data[ix] = value;
for (i; i < m_length; i++)
{
n_data[i + 1] = m_data[i];
}
delete[] m_data;
m_data = n_data;
}
void remove(const int& ix)
{
m_length -= 1;
int* n_data = new int[m_length];
int count = ix;
for (int i = 0; i < ix; i++)
{
n_data[i] = m_data[i];
}
for (count; count < m_length; count ++)
{
n_data[count] = m_data[count+1];
}
delete[] m_data;
m_data = n_data;
}
void push_back(const int& value)
{
this->m_length += 1;
int* n_data = new int[m_length];
for (int i = 0; i < m_length; i++)
n_data[i] = m_data[i];
n_data[m_length-1] = value;
delete[] m_data;
m_data = n_data;
}
friend ostream& operator << (ostream& out, IntArray& ia)
{
for (int i = 0; i < ia.m_length; i++)
out << ia.m_data[i] << " ";
out << endl;
return out;
}
};
int main()
{
IntArray my_arr{ 1, 3, 5, 7, 9 };
cout << my_arr << endl;
my_arr.insertBefore(10, 1);
cout << my_arr << endl;
my_arr.remove(2);
cout << my_arr << endl;
my_arr.push_back(13);
cout << my_arr << endl;
my_arr.initialize({ 1, 2, 3 });
cout << my_arr << endl;
return 0;
}
피드백 받고싶은 이유는 함수를 구현할 때 Array에 int를 추가, 삭제, 수정을 할때
새로 동적할당을 받은 뒤에 그 공간에 기존 데이터를 복사해주며 추가,삭제,수정 해줄 부분을 해주고
기존 동적할당 공간은 지우고 기존 객체가 가르키는 포인터를 새로 할당한 공간으로 설정 해주었습니다.
선생님 께서 예시로 작성하는 코드 짜임새와 코드라인수에 비해
제 머리속에서 나온 그대로를 코드로 담은거라 너무 조잡 난해하다는 생각이 들었습니다.
그래서 코드를 더 간단하게 짜려면 이 내용을 어떤식으로 수정하면 좋을지 피드백 받고싶습니다.
혹은 코드에 아쉬운점들을 고수분들의 관점으로 보고 말씀해주시면 배워보고싶습니다 감사합니다.
답변을 작성해보세요.
0
답변 1