Question about vector iterator in template functions(关于模板函数中向量迭代器的问题)
问题描述
我正在尝试学习 STL 库,但遇到了一个奇怪的问题.这段代码编译完美:
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;
}
错误是:
$ 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.
推荐答案
你需要说typename vector
.
另一方面,您正在按值传递 vector
.这意味着整个 vector
在函数调用中被复制.void Show(vector<T> const &myvec)
并使用 const_iterator
会更明智.
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.
这篇关于关于模板函数中向量迭代器的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:关于模板函数中向量迭代器的问题


基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01