-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
IntArray 클래스 구현에 대해 feedback받을 수 있을까요?
20.12.21 22:26 작성 조회수 220
3
안녕하세요, 질문은 아니라서 문의드리는 내용에 대해 피드백을 받을 수 있을지는 모르겠지만, 조그만 피드백이라도 쥐면 공부하는데 큰 도움이 될 것 같습니다. 감사합니다.
--------------------------
#include <iostream>
#include <initializer_list>
using namespace std;
class IntArray
{
private:
int m_length = 0;
int *m_data = nullptr;
public:
IntArray(const int &length_in)
:m_length(length_in)
{
m_data = new int[m_length];
}
IntArray(const std::initializer_list<int> &list)
:IntArray(list.size())
{
int count = 0;
for (auto &e : list)
{
m_data[count] = e;
count++;
}
}
IntArray& resize(const int& length_in)
{
if (m_length == length_in)
return *this;
else if (m_length < length_in) //길이가 길어진 경우, 뒤에 0 붙임
{
int *temp = new int[length_in];
for (int i = 0; i < m_length; i++)
temp[i] = m_data[i];
for (int i = m_length; i < length_in; i++)
temp[i] = 0;
m_length = length_in;
delete[] m_data;
m_data = temp;
}
else //길이가 짧아진 경우
{
m_length = length_in;
int *temp = new int[m_length];
for (int i = 0; i < m_length; i++)
temp[i] = m_data[i];
delete[] m_data;
m_data = temp;
}
return *this;
}
IntArray& insertBefore(const int &val, const int &idx) //10 1
{
//1 3 5 7 9
//1 3 5 7 9 0
//1 10 3 5 7 9
resize(m_length + 1);
//input index 이전 : 변화없음
//input index 이후
for (int i = m_length-1; i > idx; i--)
{
m_data[i] = m_data[i - 1];
}
//input index 값
m_data[idx] = val;
return *this;
}
IntArray& remove(const int &idx) //3
{
//1 10 3 5 7 9
//1 10 3 7 9
//concept : index 해당 element 로 하나씩 앞으로 당기고, resize (m_length-1);
for(int i=idx;i<m_length-1;i++)
m_data[i] = m_data[i + 1];
resize(m_length - 1);
return *this;
}
IntArray& push_back(const int &val)
{
resize(m_length + 1);
m_data[m_length - 1] = val;
return *this;
}
IntArray& operator =(const std::initializer_list<int> &list)
{
delete[] m_data;
m_length = list.size();
m_data = new int[m_length];
int count = 0;
for (auto &e : list)
{
m_data[count] = e;
count++;
}
return *this;
}
friend ostream& operator <<(ostream &out, const IntArray &int_arr)
{
for (int i = 0; i < int_arr.m_length; i++)
out << int_arr.m_data[i] << " ";
return out;
}
~IntArray()
{
delete[] m_data;
}
};
int main()
{
IntArray my_arr{ 1, 3, 5, 7, 9 };
cout << my_arr << endl;
my_arr.insertBefore(10, 1);//1 10 3 5 7 9
cout << my_arr << endl;
my_arr.remove(3); //1 10 3 7 9
cout << my_arr << endl;
my_arr.push_back(13); //1 10 3 7 9 13
cout << my_arr << endl;
}
답변을 작성해보세요.
3
안소
2020.12.22
안녕하세요!
제가 완전 꼼꼼히 본건 아니라서 놓친 부분이 있을 수도 있지만 작성을 다 잘 해주신 것 같아요.
쪼끔 더 추가로 보완해주시면 좋았겠다 싶은 부분은 이니셜라이저 리스트를 받는 대입 연산자만 구현을 하셨는데
IntArray my_arr{ 1, 3, 5, 7, 9 };
IntArray my_arr2;
my_arr2 = my_arr; // ⭐⭐
대입은 이런 식으로 같은 타입(IntArray)의 다른 객체로부터 대입 받는 경우가 더 많아요.
그래서 이런식으로 같은 타입의 객체로부터 대입 받는 이런 대입 연산자도 구현해주시면 더 좋았을 것 같아요!
그냥 추가적인 부분일뿐입니다 ㅎㅎ
디폴트 생성자도 추가로 넣고 실행해봤어요.
0
답변 2