c++ - 使用模板传递时访问 vector 元素

标签 c++ templates vector

<分区>

我想打印 vector 的元素。以下是我的代码。

This is my code

经过搜索,我发现了以下代码及其工作原理:

for(int i=0;i<vec.size();i++)
    cout<<vec[i]<<" ";

但是我们不能使用迭代器来访问元素吗?如果可能,怎么做?

最佳答案

typename 丢失:

template <typename T>
void printArray(const std::vector<T>& a)
{
    for (typename std::vector<T>::const_iterator it = a.begin(); it != a.end(); ++it) {
        // ...
    }
}

在c++11中,你可以简单的写:

template <typename T>
void printArray(const std::vector<T>& a)
{
    for (const auto& e : a) {
        std::cout << e << std::endl;;
    }
}

关于c++ - 使用模板传递时访问 vector 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34928590/

相关文章:

C++ 3D vector 更新 malloc 不正确的校验和

c++ - 在头文件c++中重新定义函数

c++ - C++ boost::filesystem 如何检测路径是文件还是目录?

c++ - 禁止使用模板化的虚拟成员函数,有替代方法吗?

c++ - "Invalid use of incomplete type"使用模板化类型和命名空间

c++ - 为什么 C++11 不将 lambda 隐式转换为 std::function 对象?

C++ 在 keybd_event() 上发送带有 WM_KEYDOWN 的虚拟键

c++ - 从 C++ DLL 编辑 Delphi 记录

c++ - libpng 在 png_write_into 上崩溃(Windows 10,VS2013,自建,所有测试通过 ok)

c++ - 使用 vector 的合并排序 C++