[問題] STL的iterator使用template的問題

看板C_and_CPP (C/C++)作者 ( )時間15年前 (2011/01/03 15:26), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串1/2 (看更多)
想請問各位高手們.. 今天有兩個vector容器,型別分別是int及double, 我利用template的方式把iterator指向該二容器, 程式碼如下,但是跑不過去.... #include "stdafx.h" #include <cstdlib> #include <iostream> #include <vector> using namespace std; template <class T> void PrintOut(T& container) { if (container.empty()) cout << "容器為空..."; else { vector<T>::iterator ptr; //宣告指位器 cout << "容器內資料為:"; for(ptr=container.begin();ptr!=container.end();ptr++) cout << *ptr << " "; cout << "\n\n"; } } int _tmain(int argc, _TCHAR* argv[]) { vector<int> container(2); vector<double> box(4); container[0]=1; container[1]=2; PrintOut(container); box[0]=9.3; box[1]=8.8; PrintOut(box); system("PAUSE"); return 0; } 錯誤訊息: error C2679: 二元運算子 '=' : 找不到使用右方運算元型別 'std::_Vector_iterator<_Ty,_Alloc>' 的運算子 (或是沒有可接受的轉換) 不過今天如果我把double或int其中一個先拿掉, 再將PrintOut函式中 vector<T>::iterator ptr 改成 vector<int>::iterator ptr 或是 vector<double>::iterator ptr 就可以跑得過去了..... 想請問一下我在樣板的部份撰寫上有什麼錯誤嘛? 感謝各位~~~~~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.170.116.2

01/03 15:53, , 1F
你先前的 T = vector<int> (==!
01/03 15:53, 1F

01/03 16:49, , 2F
謝謝~~ 修改後可以了 :)
01/03 16:49, 2F
文章代碼(AID): #1D8NeWCC (C_and_CPP)
文章代碼(AID): #1D8NeWCC (C_and_CPP)