C++ list
STL list는 이중 연결 리스트 방식으로 구현되어있다.
생성자 |
|
list li |
빈 컨테이너 리스느 li 생성 |
list li(n) |
리스트 li는 기본값으로 초기화된 n개의 원소를 가짐 |
list li(n, x) |
리스트 li는 x로 초기화된 n개의 원소를 가짐 |
list li(li2) |
리스트 li는 li2의 복사본 |
list li(b, e) |
리스트 li는 반복자 구간 [b, e)로 초기화된 원소를 가짐 |
생성자 사용 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> #include <list> using namespace std; int main(void) { list<int> v1; //길이 = 0 list<int> v2(100); //길이 = 100 list<int> v3(100, 5); //길이 = 100, 5로 초기화 list<int> v4 = { 1, 2, 3, 4, 5 }; //길이 5 cout << "v1 크기 : " << v1.size() << '\n'; cout << "v2 크기 : " << v2.size() << '\n'; cout << "v3 크기 : " << v3.size() << '\n'; cout << "v4 크기 : " << v4.size() << '\n'; return 0; } | cs |
주요 멤버 함수
empty() |
리스트가 비어있는가? |
size() |
리스트의 크기 반환 |
front() |
리스트의 첫번째 원소에 접근 |
back() |
리스트의 마지막 원소에 접근 |
push_front() |
리스트의 가장 앞에 데이터 추가 |
pop_front() |
리스트의 첫 데이터 제거 |
push_back() |
리스트의 가장 뒤에 데이터 추가 |
pop_back() |
리스트의 마지막 데이터 제거 |
insert() |
리스트의 특정 위치에 데이터 삽입 |
erase() |
리스트의 특정 구간 데이터 제거 |
사용 예제
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #include <iostream> #include <list> int main() { std::list<int> mylist; std::list<int>::iterator it1; int sum(0); mylist.push_back(300); //300 mylist.push_back(400); //300 400 mylist.push_back(500); //300 400 500 mylist.push_front(200); //200 300 400 500 mylist.push_front(100); //100 200 300 400 500 while (!mylist.empty()) { sum += mylist.front(); mylist.pop_front(); } std::cout << "The elements of mylist add up to " << sum << '\n'; // set some values: for (int i = 1; i<10; ++i) mylist.push_back(i * 10); // 10 20 30 40 50 60 70 80 90 it1 = mylist.begin(); // ^^ ++it1; // ^ it1 = mylist.erase(it1); // 10 30 40 50 60 70 80 90 // ^ std::cout << "mylist contains:"; for (it1 = mylist.begin(); it1 != mylist.end(); ++it1) std::cout << ' ' << *it1; std::cout << '\n'; //resize mylist.resize(2); //10 30 std::cout << "my list size : " << mylist.size() << '\n'; //clear mylist.clear(); // std::cout << "my list size : " << mylist.size() << '\n'; for (int i = 1; i <= 10; i++) mylist.push_back(i);//1 2 3 4 5 6 7 8 9 10 std::list<int>::iterator it = mylist.begin(); ++it; it = mylist.insert(it, 20); //1 20 2 3 4 5 6 7 8 9 10 mylist.insert(it, 2, 30); //1 30 30 20 2 3 4 5 6 7 8 9 10 std::cout << "mylist contains:"; for (it = mylist.begin(); it != mylist.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; } | cs |
참조: http://www.cplusplus.com/reference/list/list/
참고문헌: 뇌를 자극하는 C++ STL
'컴퓨터공학 > STL' 카테고리의 다른 글
[STL] C++ STL set (0) | 2018.07.22 |
---|---|
[STL] C++ STL string to int/float/double/long long (0) | 2018.07.19 |
[STL] C++ STL deque (0) | 2018.07.19 |
[STL] C++ STL vector (0) | 2018.07.19 |
[STL] C++ STL string (0) | 2018.07.19 |