data 컨테이너는 초기화 리스트의 값으로 설정된 원소들로 생성된다. 첫 번째 copy() 호출은 istream_iterator 객체가 첫 번째 인수이므로 표준 입력 스트림에서 double 타입의 값을 읽어 들인다. 두 번째 인수는 스트림 반복자를 위한 끝 스트림이며 istream_iterator는 스트림의 끝에 도달하면 이 값을 갖게 된다. 즉, 키보드에서 Ctrl+Z를 입력하면 cin에서 스트림의 끝에 도달하게 된다. copy()의 세 번째 인수는 읽어 들인 값을 쓸 대상을 지정하며, 이는 back_inserter() 함수가 반환한 back_insert_iterator가 된다. 따라서 cin에서 읽어 들인 값들이 data 컨테이너의 끝에 새 원소로 추가된다. 마지막 문장의 copy() 호출은 data 컨테이너의 모든 원소를 cout에 복제한다. 이는 ostream_iterator 객체를 대상으로 지정해서 할 수 있다. vector 컨테이너에서 반복자를 사용하는 완전한 예제를 살펴보자.
// Ex2_02.cpp // vector 컨테이너에 저장된 문자열 정렬하기 #include <iostream> // 표준 스트림 #include <string> // string 타입 #include <algorithm> // swap()과 copy() 함수 #include <vector> // 벡터 #include <iterator> // 반복자 using std::string; using std::vector; int main() { vector<string> words; // 정렬할 단어를 저장 words.reserve(10); // 원소들을 위한 공간 할당 std::cout << “단어는 공백으로 구분해서 입력하세요. 종료하려면 다음 줄에서 Ctrl+Z를 입력하세요:” << std::endl; std::copy(std::istream_iterator<string> {std::cin}, std::istream_iterator<string> {}, std::back_inserter(words)); std::cout << “정렬을 시작합니다.” << std::endl; bool out_of_order {false}; // 값들이 정렬되지 않았으면 true auto last = std::end(words); while (true) { for (auto first = std::begin(words) + 1; first != last; ++first) { if (*(first - 1) > *first) { // 정렬되지 않았으니 값을 교환한다 std::swap(*first, *(first - 1)); out_of_order = true; } } if (!out_of_order) // 정렬된 상태이면(교환이 필요 없음)… break; // …완료… out_of_order = false; // …그렇지 않으면, 다시 반복 } // 정렬된 벡터를 출력 std::cout << “오름차순으로 정렬된 단어:” << std::endl; std::copy(std::begin(words), std::end(words), std::ostream_iterator<string> {std::cout, ” “}); std::cout << std::endl; // words 벡터에서 원소들을 이동해서 새 벡터를 생성 vector<string> words_copy {std::make_move_iterator(std::begin(words)), std::make_move_iterator(std::end(words)) }; std::cout << “\nwords에서 원소들을 이동한 후에 words_copy의 내용:” << std::endl; std::copy(std::begin(words_copy), std::end(words_copy), std::ostream_iterator<string> {std::cout, ” “}); std::cout << std::endl; // words 벡터의 원소들에 무슨 일이 일어났는지 알아보기… std::cout << “\nwords 벡터는 원소 “ << words.size() << “개를 갖고 있습니다.\n“; if (words.front().empty()) std::cout << “첫 번째 원소는 빈 문자열 객체입니다.” << std::endl; std::cout << “첫 번째 원소는 \”“ << words.front() << “\”입니다.” << std::endl; }