c·c++/c++ 프로그래밍

C++에서 STL 사용하지 않고 가변배열 만들 수 없나요?

바로이순간 2014. 7. 16. 03:18

// 빠르고 메모리 낭비가 적은 가변배열을 만들어 봅니다.

#include <iostream>

#include <string>

using namespace std;

class SimpleStringArray {

//define private member functions

private:

    int size1;    // 1st array size;

    int size2;    // 2nd array size;

    int index;    // next index

    string** table;  // array

public:

    // 초기화를 하면 크기 size2만큼의 table과

    // 크기 size1만큼의 table[0]이 생성이 된다.

    // 최대크기 size1*size2에 비교하면 

    // size1+size2의 필요한 메모리는 충분히 작다고 할 수 있다.

    SimpleStringArray(int n1, int n2) {

        size1=n1;

        size2=n2;

        index=0;

        table=new string*[size2];

        table[0]=new string[size1];

    }

    void addLast(string s);

    int length() {

        return index;

    }

    string at(int i) {

        if(i<index) {

            return table[i/size1][i%size1];

        } else {

            return "";

        }

    }

};

void SimpleStringArray::addLast(string s) {

    table[index/size1][index%size1]=s;

    index+=1;

    // index가 최대크기 size1*size2가 되면 오류이다.

    // 오류를 일으키는 대신 table의 크기를 2배로 만들어 주는 방법을 채택할 수도 있다.

    if(index>=size1*size2) {

        cout<<"Array Full Error"<<endl;

        return;

    }

    if(index%size1==0) {

        table[index/size1]=new string[size1];

    }

}

int main() {

    // 필요한 배열의 크기에 따라서 두 인자를 주도록 한다.

    // 이상적으로는 sqrt(최대배열의 크기) 만큼씩으로 두 인자를 주는 방법이 좋다고 본다.

    // 물론 size1을 적게 주고 size2를 크게 주어서 size1*size2==최대배열의 크기로 줄 수도 있다.

    SimpleStringArray arr(5, 5);

    string line;

    int i=0;


    while(1) {

        getline(cin, line);

        if(line.length()<1) break;

        arr.addLast(line);

    }

    for(int i=0;i<arr.length();i+=1) {

        cout<<arr.at(i)<<endl;

    }

        

    return 0;

}

'c·c++ > c++ 프로그래밍' 카테고리의 다른 글

next_permutation  (0) 2014.07.22
next_number  (0) 2014.07.22
Fraction Class  (0) 2014.05.12
bool 형에 대해서  (0) 2014.04.02
longest common substring  (0) 2014.03.31