编写一个函数,无论类型如何,都打印 STL 向量的每个元素
我尝试使用这段代码,但它不起作用
template <class T>
void display(vector<T> vec)
{
vector<T>::iterator MyIter;
for(MyIter=vec.begin();MyIter!=vec.end();MyIter++)
cout<<*MyIter<<" ";
cout<<endl;
}
我的意思是是否有一种方法可以避免为每种类型 T (int、char、string)创建函数。我只使用 T 的内置类型。
这是我编译程序时的错误消息
10 C:\Documents and Settings\ASPIRE\Desktop\perms.cpp expected `;' before "MyIter"
I tried with this piece of code but it didn't work
template <class T>
void display(vector<T> vec)
{
vector<T>::iterator MyIter;
for(MyIter=vec.begin();MyIter!=vec.end();MyIter++)
cout<<*MyIter<<" ";
cout<<endl;
}
I mean if there's a way of avoid making a function for each type T (int, char, string). I'm using only builtin types for T.
This is the error message when I compile the program
10 C:\Documents and Settings\ASPIRE\Desktop\perms.cpp expected `;' before "MyIter"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您缺少变量定义
MyIter
前面的typename
,即它应该是typename vector::iterator MyIter;
You are missing the
typename
infront of the variable definitionMyIter
i.e. it should betypename vector<T>::iterator MyIter;
您能更清楚地了解这段代码如何不起作用吗?
它依赖于 T::operator<< 的存在。 - 如果您在代码中使用的任何实例化类型/类 T 都不存在,则代码将无法编译。对于内置类型,此代码可以正常工作。如果您将其用于您自己类型的向量,那么您将必须实现运算符<<每个人都可以做到这一点。
顺便说一句,使用
++MyIter
,它的效率更高。Can you be more clear on how this code did not work?
It relies on the existence of T::operator<< - if that is not present for any instantiating type/class T that you use in your code, the code will not compile. For builtin types this code would work OK. If you are using this for vector of your own types then you would have to implement operator<< for each for this to work.
btw use
++MyIter
, it's more efficient.