STL 처음시작하는데 도와주세요.
#include <iostream> #include <vector> #include <list> #include <set> #include <string> #include <iterator> using namespace std; template<typename Container> void PrintContainer(string strTitle, Container &cont); int main() { int pArray[5] = {9,1,4,7,2}; list<int> l; copy(pArray, pArray+5, front_inserter(l)); PrintContainer("Post",l); vector<int> v; for(int i=0;i<5;i++) back_inserter(v) = pArray[i]; PrintContainer("Back",v); set<int> s; copy(pArray,pArray+5,inserter(s,s.begin())); PrintContainer("Insert",s); return 0; } template<typename Container> void PrintContainer(string strTitle, Container &cont) { cout << strTitle << ":"; for(Container::iterator it = cont.begin(); it != cont.end(); ++it) { cout.width(3); cout << *it; } cout << endl; }
저렇게 작성했는데 에러가 납니다.
개인적으로 틀린게 없다고 생각하는데 말이죠...
책에 있는 소스 그냥 썼는데(책에는 VC.net으로 돌렸습니다.)
하지만 책에서 Standard Library의 중요성을 강조했는데
리눅스하고 VC하고 틀리면 무슨 소용일까 생각합니다.
혹시 제가 잘못한게 있을까요 빼먹은거나
<>깨질게 분명하기에 작성한 소스 올려드립니다.
글고 kldp.org에서 cpp 못올리게 해서 확장자 txt로 고쳤습니다.
밑에는 에러표시줄이요...
kirina@kirina:~/stl$ g++ first.cpp
first.cpp: In function ‘void PrintContainer(std::string, Container&)’:
first.cpp:32: error: expected `;' before ‘it’
first.cpp:32: error: ‘it’ was not declared in this scope
first.cpp: In function ‘void PrintContainer(std::string, Container&) [with Container = std::list >]’:
first.cpp:17: instantiated from here
first.cpp:32: error: dependent-name ‘Container::iterator’ is parsed as a non-type, but instantiation yields a type
first.cpp:32: note: say ‘typename Container::iterator’ if a type is meant
first.cpp: In function ‘void PrintContainer(std::string, Container&) [with Container = std::vector >]’:
first.cpp:21: instantiated from here
first.cpp:32: error: dependent-name ‘Container::iterator’ is parsed as a non-type, but instantiation yields a type
first.cpp:32: note: say ‘typename Container::iterator’ if a type is meant
first.cpp: In function ‘void PrintContainer(std::string, Container&) [with Container = std::set, std::allocator >]’:
first.cpp:24: instantiated from here
first.cpp:32: error: dependent-name ‘Container::iterator’ is parsed as a non-type, but instantiation yields a type
first.cpp:32: note: say ‘typename Container::iterator’ if a type is meant
첨부 | 파일 크기 |
---|---|
![]() | 841바이트 |
typename 키워드에 대해 알아보세요
그리고 문법 에러와는 관계없지만
string 같은 객체를 넘길 때는 참조를 사용하세요.
읽기 전용으로 넘기신다면 상수 참조를 사용하시고요.
템플릿 사용에 대해 좀더 알아보시고 예제를 따라 차근차근 공부하시기 바랍니다.
그리고 방금 전에 거의 똑같은 코드를 올리셔서 http://kldp.org/node/90835
다른 분들이 이미 답변해 주신 것 같은데 왜 또 올리시죠?
[예진아씨 피카사 웹앨범] 임예진 팬클럽 ♡예진아씨♡ http://cafe.daum.net/imyejin
댓글 달기