VioletaBabel

10일 : 템플릿, STL(리스트, 맵) 본문

BCA/1. C,C++,C#
10일 : 템플릿, STL(리스트, 맵)
Beabletoet 2018. 2. 21. 10:35

템플릿

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
using namespace std;
template<typename t, typename u>t add(t a, u b)
{
    return a + b;
}
template<typename t>class c
{
private:
    t ans;
public:
    t add(t a, t b)
    {
        ans = a + b;
        return ans;
    }
};
int main()
{
    cout << add(12<< endl;//3
    cout << add(1.12<< endl;//3.1
    cout << add(1.32.2<< endl;//3.5
    cout << add(12.1<< endl;//3
    c<int> a;//클래스는 무조건 타입을 미리 잡아줘야함
    cout << a.add(12<< endl;//3
}
cs


--

리스트(링크드 리스트)

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include<list>
using namespace std;
int main()
{
    list<int> l;
    l.push_back(10);
    l.push_back(20);
    l.push_back(30);
    l.push_front(5);
    for (list<int>::iterator i = l.begin(); i != l.end(); ++i)
        cout << *<< endl;
}
cs


--

맵(이진 트리)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
    map<intstring> d;//왼쪽은 키, 오른쪽은 찾을 수 있는 데이터.
    d[5= "abcd";//이진 트리로 들어간다.
    d[15= "efg";
    d[2= "hijklmn";
 
    map<stringint>d2;
    d2["hp"= 50;
    d2["mp"= 60;
    d2["atk"= 15;
 
    cout << d.find(5)->second.c_str() << endl;//abcd
    cout << d2.find("hp")->second << endl;//50
    cout << d2["atk"<< endl;//15
    
    map<stringint>::iterator i = d2.find("mp");//mp 위치를 찾는다
    cout << i->second << endl;//60
 
    i = d2.find("dwiqhdioqwhid");
    if (i != d2.end())//값을 찾았을 경우
        cout << i->second << endl;
    else//값을 못 찾았을 경우
        cout << "none" << endl;
    
    i = d2.begin();
    cout << i->second << i->first << endl;//15atk
 
    i = d2.end();
    cout << i->second << endl;//에러!!!! begin은 첫 원소의 위치지만 end는 마지막 원소의 다음 위치라 비어있다!
}
cs



--


'BCA > 1. C,C++,C#' 카테고리의 다른 글

52. A* 알고리즘  (0) 2018.07.09
17일 : class 선언과 include의 차이  (0) 2018.03.09
9일 : 다형성을 이용해 간단한 텍스트 RPG 만들기  (0) 2018.02.20
8일 : 상속과 다형성  (0) 2018.02.19
7일 : 연산자 오버로딩  (0) 2018.02.13
Comments