14. STL - haptics.khu.ac.krhaptics.khu.ac.kr/aoop/lab10_ch14_part1.pdf · 14. STLㅣ Practice 1...
Transcript of 14. STL - haptics.khu.ac.krhaptics.khu.ac.kr/aoop/lab10_ch14_part1.pdf · 14. STLㅣ Practice 1...
14. STL
2
14. STL
3
14. STL
4
STL 컨테이너 특 징
vector - 동적 배열이므로 배열의 크기를 변경할 수 있다.
- 임의 접근이 가능하며, 뒤에서의 삽입이 빠르다.
list - 연결 리스트이므로 데이터를 순차적으로 접근하고 관리할 때 유용하다.
- 위치에 상관없이 삽입과 삭제가 빠르다.
deque - 데크라고 한다.
- 임의 접근이 가능하며, 앞과 뒤에서의 삽입이 빠르다.
map - 특정 키(key)에 의해서 데이터를 접근하고 관리할 수 있다
- 키를 통해 값을 접근하며, 삽입과 삭제가 빠르다.
set - 원소들을 순서대로 관리하며, 소속 검사와 삽입, 삭제가 빠르다.
- 중복된 원소를 허용하지 않는다.
stack - top에서만 삽입과 삭제가 가능하다.
- LIFO(Last In First Out) 방식으로 데이터를 삽입, 삭제 한다.
queue - 삽입은 뒤쪽에서, 삭제는 앞쪽에서 수행한다.
- FIFO(First In First Out) 방식으로 데이터를 삽입, 삭제 한다.
순차 컨테이너
연관 컨테이너
어댑터 컨테이너
14. STL
5
14. STL
6
14. STLㅣ Practice 1
7
14. STLㅣ Practice 1
출처 : www.hanb.co.kr/network
배열에서의 데이터 삽입 연결 리스트에서의 데이터 삽입
14. STLㅣ Practice 1
names
“Eric” “Samsic” “Daniel”
14. STLㅣ Practice 1
목표 : List 컨테이너의 활용
#include <list>
#include <algorithm>
using namespace std;
class Member
{
public:
Member(string f, string l) :
first_n(f), last_n(l) {}
void print(){
cout << last_n<<“ “ << first_n << endl;
}
private:
string last_n, first_n;
friend bool operator < (Member& m1,
Member& m2) { return m1.last_n < m2.last_n; }
friend bool operator == (Member& m1, Member& m2)
{ return m1.last_n == m2.last_n; }
};
output
int main ()
{
list<Member> li1;
li1.push_back(Member("Linda","Smith"));
li1.push_back(Member("Robert","Frost"));
li1.push_back(Member("Alex","Amstrong"));
list<Member> li2;
li2.push_back(Member("Linda","Smith"));
li2.push_back(Member("John","Wood"));
li2.push_back(Member("Alex","Amstrong"));
li1.sort();
li2.sort();
li1.merge(li2);
cout << "li1 after sorting and mergin"
<< endl;
list<Member>::iterator it = li1.begin();
while ( it != li1.end() ) (it++)->print();
li1.unique();
cout << "After li1.unique()" << endl;
it = li1.begin();
while ( it != li1.end() ) (it++)->print();
return 0;
}
• Member클래스를 작성하고, list를 2개 생성하여 통합 후 중복 데이터를 제거하라.
14. STLㅣ Practice 1
14. STLㅣ Practice 1
출처 : www.hanb.co.kr/network 중간에 데이터 삽입 중간에 데이터 삭제
14. STLㅣ Practice 1
nums
14 -999 57
[0] [1] [2]
14. STLㅣ Practice 1
목표 : Vector 컨테이너의 활용
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
class Member
{
public:
Member(string t, double d) : name(t), sal(d) {}
void print();
{
cout << name << " "<< sal <<endl;
}
private:
string name;
double sal;
};
output
int main()
{
vector<Member> v;
int i;
v.push_back(Member("Linda", 75000));
v.push_back(Member("Robert", 60000));
vector<Member>::iterator it = v.begin();
cout << "Entire vector(using iterator):" <<endl;
// Iterator를 이용하여 전체 원소 출력
while(it != v.end())
(it++)->print();
cout <<endl;
cout << “Entire vector(random access):” <<두이;
// 랜덤 접근을 통한 vector 전체 원소 출력
for(i=0; i<v.size(); i++)
v[i].print();
cout << endl;
cout << "Return from front()" <<endl;
v.front().print();
return 0;
}
• Member 클래스를 데이터로 갖는 Vector의 첫 번째 요소를 출력하여라.
14. STLㅣ Practice 1
출처 : www.hanb.co.kr/network
Vector List
크기 변경 가능 O O
중간 삽입, 삭제 용이 X O
순차 접근 가능 O O
랜덤 접근 가능 O X
14. STLㅣ Practice 1
출처 : www.hanb.co.kr/network 실제 나무와 트리 자료구조의 예
14. STLㅣ Practice 1
m
“zero”
“one”
“phone”
0
1
12345
Key(first) Value(second)
14. STLㅣ Practice 1
목표 : Map 컨테이너의 활용
int main ()
{
map<string, string> dictionary;
string searchWord;
// 사전에 단어 입력
//(1) operator [] 를 이용한 입력 : overwrite 가능
dictionary["horse"] = "말";
dictionary["apple"] = "사과";
//(2) insert 메소드를 이용한 입력 : overwrite 불가
dictionary.insert(pair<string,string>("grape","포도"));
dictionary.insert(pair<string,string>("orange","오렌지"));
// 영어 단어를 이용한 검색
cout << "검색하고자 하는 영어 단어를 입력하세요 : ";
cin >> searchWord;
if(!dictionary[searchWord].empty())
{
cout <<"단어를 찾았습니다."<<endl;
cout << searchWord << " : " << dictionary[searchWord] <<endl;
}else
{
cout <<"검색된 단어가 없습니다."<<endl;
}
return 0;
}
output
• <영어단어, 뜻> 의 쌍으로 구성되는 Map 자료구조 dictionary를 선언하고, 사용자로부터 영어단어를 입력 받아 뜻을 출력하여라.
※ 동일하게 동작하도록 first, second를 이용하여 구현. (이전 페이지 참조) map<string, string>::iterator it; it = dictionary.find(searchWord); if(!(*it).second.empty()) { cout <<"단어를 찾았습니다."<<endl; cout << _______ << " : " << ________<<endl; }else { cout <<"검색된 단어가 없습니다."<<endl; }
14. STLㅣ Practice 1
출처 : www.hanb.co.kr/network
14. STLㅣ Practice 1
50
20 80
10 30 70 90
14. STLㅣ Practice 1
목표 : Set 컨테이너의 활용
class Member
{
public:
Member(string l, string f) : last(l), first(f){}
void print() const
{
cout.setf(ios::left);
cout << setw(15) << first << " "<< last <<endl;
}
private:
string first, last;
friend bool operator <
(const Member& m1, const Member& m2)
{
return (m1.last < m2.last) ? true : false;
}
friend bool operator ==
(const Member& m1, const Member& m2)
{
return (m1.last == m2.last) ? true : false;
}
};
output
int main ()
{
typedef Member M;
typedef set<M> S;
M m("Frost","Robert");
S s;
s.insert(m);
s.insert(M("Smith","John"));
s.insert(M("Amstrong","Bill"));
s.insert(M("Bain","Linda"));
s.insert(M(“Amstrong”,”Bill”)); //두 번째 입력과 동일
/* 기존에 존재하는 값들과 비교하여, 동일한 값이 이미 존재
할 경우 값을 추가하지 않는다. 이 동작은 operator ==를
통해 이루어진다. */
S::iterator it = s.begin();
while ( it != s.end() )
(it++)->print();
it = s.find(m);
if ( it == s.end() )
cout << "element not found" << endl;
else
{
cout << "element is found : ";
(*it).print();
}
return 0;
}
• Member 객체를 데이터로 갖는 Set을 구성하고, Frost Robert가 존재하는지 검색하여라.
14. STLㅣ Practice 1
출처 : www.hanb.co.kr/network
14. STLㅣ Practice 1
목표 : sort 알고리즘 활용
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void main( )
{
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(50);
v.push_back(20);
v.push_back(40);
for(int i = 0 ; i < v.size() ; i++)
cout << v[i] << " ";
cout << endl;
sort(v.begin(), v.end());
for(int i = 0 ; i < v.size() ; i++)
cout << v[i] << " ";
cout << endl;
}
output
• Int 자료형의 Vector를 구성하여, STL의 sort 알고리즘을 이용하여 정렬하여라.
14. STLㅣ Practice 1
20을 검색할 때, 순차 탐색을 할 경우 9회 탐색에 검출되지만 이진 탐색을 사용하면 3회 탐색에 검출된다.
14. STLㅣ Practice 1
목표 : Binary search 알고리즘 활용
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main( )
{
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);
if( binary_search(v.begin(), v.end(), 20) )
cout << "20 있음!" << endl;
else
cout << "20 없음!" << endl;
if( binary_search(v.begin(), v.end(), 15) )
cout << "15 있음!" << endl;
else
cout << "15 없음!" << endl;
}
output
• Int 자료형의 Vector를 구성하여, STL의 sort 알고리즘을 이용하여 정렬하여라.
14. STLㅣ Practice 1