关于模板函数中的向量迭代器的问题 [英] Question about vector iterator in template functions
本文介绍了关于模板函数中的向量迭代器的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图学习STL库,我有一个奇怪的问题。此代码完全编译:
void Show(vector< int> myvec)
{
vector< int> ; :: iterator it;
cout<< Vector contains:;
for(it = myvec.begin(); it< myvec.end(); it ++)
{
cout< < *它;
}
cout<< endl;
}
而这一个在编译时给我一个错误信息:
模板< class T>
void Show2(vector< T> myvec)
{
vector< T&
cout<< Vector contains:;
for(it = myvec.begin(); it< myvec.end(); it ++)
{
cout< < *它;
}
cout<< endl;
}
错误是:
$ g ++ hello.cpp
hello.cpp:在函数'void Show2(std :: vector< T,std :: allocator< _Tp1>
hello.cpp:19:error:expected';'before'it'
hello.cpp:21:error:'it'未在此范围内声明
这看起来是一个很简单的错误,但我找不到。
解决方案
您需要说 typename向量< T> :: iterator it
。
另一方面,你通过值向量
。这意味着整个向量
在函数调用中被复制。 void Show(vector< T> const& myvec)
并使用 const_iterator
会更聪明。 b $ b
I'm trying to learn the STL library and I'm having a weird problem. This code compiles perfectly:
void Show(vector<int> myvec)
{
vector<int>::iterator it;
cout << "Vector contains:";
for( it = myvec.begin(); it < myvec.end(); it++)
{
cout << " " << *it;
}
cout << endl;
}
while this one gives me an error message at compile time:
template <class T>
void Show2(vector<T> myvec)
{
vector<T>::iterator it;
cout << "Vector contains:";
for( it = myvec.begin(); it < myvec.end(); it++)
{
cout << " " << *it;
}
cout << endl;
}
The error is:
$ g++ hello.cpp
hello.cpp: In function ‘void Show2(std::vector<T, std::allocator<_Tp1> >)’:
hello.cpp:19: error: expected ‘;’ before ‘it’
hello.cpp:21: error: ‘it’ was not declared in this scope
It seems a very simple mistake, but I couldn't find it.
解决方案
You need to say typename vector<T>::iterator it
.
On another note, you're passing vector
s by value. That means the entire vector
gets copied in the function call. void Show(vector<T> const &myvec)
and using const_iterator
would be wiser.
这篇关于关于模板函数中的向量迭代器的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文