#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> lst = {10, 20, 30, 40, 50, 60};
//advance()
auto it = lst.begin(); // 첫 번째 원소를 가리키는 반복자
advance(it, 2); // 2칸 이동 (30을 가리킴)
cout << *it << std::endl; // 출력: 30
//next()
cout << *next(it, 2) <<endl; //advance와 같으나 새로운 반복자 반환
//erase()
auto itErase = next(lst.begin(), 2); //30을 가리키는 반복자
itErase = lst.erase(itErase); //30 삭제
//erase()후 반복자는 무효화되므로 반환된 반복자로 갱신
auto it1 = std::next(lst.begin(), 1); // 20을 가리킴
auto it2 = std::next(lst.begin(), 3); // 50을 가리킴 (삭제되지 않음)
lst.erase(it1, it2); // 20,40 삭제
//remove()
lst.remove(10); // 모든 10 삭제, 50과 60만 남음
it = lst.begin();
advance(it, 1); //60 가리킴
auto prev_it = std::prev(it); //50 가리킴 next에 대응(새로운 반복자 반환)
//advance(it, -2);
return 0;
}
#include <iostream>
#include <list>
int main() {
std::list<int> lst = {10, 20, 30, 40, 50};
int n = 3;
if (n < lst.size()) { // 리스트 크기보다 작을 때만 이동
auto it = std::next(lst.begin(), n);
std::cout << *it << std::endl; // 출력: 40
} else {
std::cout << "Out of range!" << std::endl;
}
return 0;
}