헤더파일
컨테이너 - 2 본문
STL은 자료형이 같은 자료만 담는다.
사용자는 어떤 컨테이너를 쓴다 하더라도 이터레이터를 통해 접근할 수 있다.
반복자는 포인터와 유사한 기능을 함.
initializer_list<int> a = {1, 2, 3, 4, 5};
vector<int> vec1(a);
auto iter = vec1.begin();//읽기/쓰기용으로 접근
auto citer = vec1.cbegin();//읽기 용으로만 접근
for (auto p = v.cbegin(); p != v.cend(); ++p)
{
cout << *p << endl;
}
읽기용으로 앞에서부터 한칸씩 출력.
for (auto p = v.rbegin(); p != v.crend(); ++p)
{
cout << *p << endl;
}
뒤에서 부터 접근할 수 있다.
int main()
{
vector<string> v;
ifstream in("Lecture.cpp");
string s;
while (in >> s)
{
v.push_back(s);
}
for (auto p = v.rbegin(); p!=v.rend(); ++p)
{
string temp = *p;
for (auto n = temp.crbegin(); n != temp.crend(); ++n)
{
cout << *n;
}
cout << endl;
}
cout<< "모두: " << v.size() << " 개" << endl;
}
소스파일을 단어별로 읽고 단어를 거꾸로 읽는 작업을 편하게 할 수 있다.
Array
기존 배열의 문제점은 경계가 없어 인덱스로 유효하지 않은 값도 접근할 수 있다는 것입니다.
int main()
{
array<int,6> a{ 1,2,3,4,5,6 };
int n;
while (true)
{
cout << "몇번째 값?\n";
cin >> n;
try {
cout << a.at(n) << endl;
}
catch(exception& e)
{
cout << "올바르지 않는 입력값" << endl;
}
}
}
array도 []연산자로 접근하면 경계검사가 작동하지 않지만 at으로 접근하면 경계를 넘어서면 예외를 발생시킨다.