루리코딩 세상

STL (Standard Template Library) 본문

이론/C++

STL (Standard Template Library)

루리딩 2025. 5. 11. 10:51

Standard Template Library
STL은 다양한 자료형으로 사용 할 수 있도록 만든 함수 템플릿이나 클래스 템플릿이 기초가 된다.
type : Linked List, Array, Vector, Stack, Queue, Heap, Prinority Queue, Map, unordered_map, Set 등 다양한 템플릿을 제공한다.


연결리스트 (Linked List)
어떤 데이터 덩어리를 저장할 때 그 다음 순서의 자료가 있는 위치를 데이터에 포함시키는 방식으로 자료 저장


  • 연결리스트 ( Linked List )

#include <list>

시간복잡도
next 포인터와 prev 포인터를 가진다.
# include <iostream>
#include <list>

using namespace std;

Int main () {
list<int> temp; // 리스트 선언

// push_back -> 뒤에서 값 넣기
for (int i = 0; i<10; i++){
temp.push_back(i);
}

// push_front -> 앞에서 값 넣기
for (int i = 0; i<10; i++){
temp.push_front(i);
}

// insert (인덱스, 값)
auto index = ++temp.begin();
temp.insert(index, -1);
for (int a: temp){
cout << a << “ ”;
}
cout << end1;

// 맨 앞 원소 제거하기
temp.pop_front();
// 맨 뒤 원소 제거하기
temp.pop_back();
for (int a : temp){
cout << a << “ “;
}
return 0;
}

배열 ( Array )


순서대로 번호가 붙어 있는 같은 타입의 원소들이 연속적인 형태 (인접한 메모리 위치)로 구성된 구조.
각 원소에 붙은 번호를 인덱스(index)라고 부름
탐색을 많이 하는 경우에는 배열을 사용하는 것이 좋다. (Linked List 와 반대)

#include <iostream>

using namespace std;

int main(){
    // 배열 선언
    int temp[10];
    for (int i=0; i<10; i++){
        temp[i] = i;
    }
    for (int a: temp){
        cout << a << " ";
    }
    return 0;
}

벡터 ( Vector )


STL의 표준 컨테이너 중 하나
#include <verctor>
동적으로 요소를 할당할 수 있는 동적 배열이다.
중복을 허용하며, 순서가 있고 핸덤으로 접근이 가능하다.
#include <iostream>
#include <vector>

using namespace std;

int main(){
    // 벡터 선언
    vector<int> temp1, temp2;
    // 2차원 벡터 temp3 생성 -> 3개의 열을 갖고, 각각의 열을 '0' 원소 2개로 초기화
    vector<vector<int>> temp3 = {3, vector<int> {0, 0}};

    // emplace_back, push_back 모두 요소를 삽입하는 동일한 기능
    // 단 emplace_back은 1차원 원소만 삽입 가능
    for (int i=0; i<10; i++){
        temp1.emplace_back(i);
        temp2.push_back(i);
    }
    for (int i=0; i<10; i++){
        cout << "temp1: "<< temp1[i] << ", " << "temp2: " << temp2[i] << endl;
    }
    cout << endl;

    for (int i=0; i<temp3.size(); i++){
        cout << temp3[i][0] << " " << temp3[i][1] << endl;
    }

    temp3[0][0] = -3;
    temp3[0][1] = 3;
    temp3[1][0] = -4;
    temp3[1][1] = 4;
    temp3[2][0] = -5;
    temp3[2][1] = 5;

    for (int i=0; i<temp3.size(); i++){
        cout << temp3[i][0] << " " << temp3[i][1] << endl;
    }
    return 0;
}



'이론 > C++' 카테고리의 다른 글

C++ 스택 오버 플로우 (Stack Overflow)  (0) 2025.05.12
C++ 콘텐츠 : 포인터  (0) 2025.05.12
C++ 라이브러리  (0) 2025.05.09
string CLASS  (0) 2025.05.09
sizeof 연산자  (0) 2025.05.09