c++ - 一个在 C++ 中打印 vector 和列表的函数

标签 c++ stl

在学习标准模板库的同时

/*
Aim:Create a vector of integers. Copy it into a list, reversing as you 
do so.
*/

#include<iostream>
#include<vector>
#include<algorithm>
#include<list>
using namespace std;
template<typename t>
void print(vector <t> &v)      //what changes need to be done here?
{
    for (auto it = v.begin(); it < v.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
}
int main()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    print(v);         
    list<int> l(v.size());
    reverse_copy(v.begin(), v.end(), l.begin());
    print(l);        //cannot call this
}

问题是我想要相同的函数 print() 为我打印 vector 和列表。 我尝试执行以下操作

void print(t <t> &v);

我们能做到吗?我还看到了使用 ostream 迭代器的解决方案 用于打印容器。这能解决我的问题吗?

最佳答案

正确的方法是使用迭代器:

template <class ForwardIter>
void print(ForwardIter begin, ForwardIter end)
{
    for (; begin != end; ++begin)
        cout << *begin << " ";
    cout << endl;
}

这就是标准库函数与容器无关的方式,您也应该以这种方式编写函数。

这样做的原因是迭代器实际上是使用可迭代对象的通用方法。可以是vector、list、c array、file、socket等,你不需要知道也不需要关心。

关于c++ - 一个在 C++ 中打印 vector 和列表的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37773763/

相关文章:

c++ - 当我尝试编译我的代码时,出现从 char* 到 char 的转换错误

C++:制作对象的浅表拷贝a)语法b)我需要删除它吗

c++ - vector::max_size 的实际使用

c++ - 从 std::multimap 删除元素时的特殊行为

C++ "greater"函数对象定义

c++ - 在 C++ 中使用继承时避免不必要的函数声明/定义

c++ - 数组指针算术题

C++ - 函数、参数和指针 - 访问冲突

c++ - 如何创建可以参数化的哈希函数?

c++ - 用 std::istream_iterator 限制 std::copy 的范围