将std容器传递给函数

Pass a std container to a function

本文关键字:函数 std      更新时间:2023-10-16

我提出了以下内容:

template <typename T> inline void printcontainer( std::vector<T> container )
{
    for( auto it = container.begin(); it != container.end(); it++ )
    {
        std::cout << *it << std::endl;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<int> v;
    v.push_back(5);
    v.push_back(4);
    v.push_back(3);
    printcontainer(v);
    return 0;
}

(很抱歉push_backs,visual studio不接受初始值设定项列表…啊!!)

现在这个函数仅限于std::vector,我如何使它可以传递其他容器,如std::list数组等。

只需不模板化容器存储的类型,而是模板化容器本身的类型:

template <typename Container>
inline void printcontainer(const Container &container)

请注意,我将参数更改为const引用,以避免不必要的复制。

您可以使用非成员std::beginstd::end或使用基于范围的for循环将打印函数泛化为C数组:

template <typename Container>
inline void printcontainer(const Container &container) {
    for (const auto &v : container)
        std::cout << v << "n";
}

OT备注:您可能不需要这里的inline

传递容器对象违反了经典的Stepanov的STL容器迭代器算法通用编程风格。

通常会传递迭代器:

# define ForwardIterator typename // workaround untill we have concepts
template <ForwardIterator It> inline void printcontainer( It begin, It end )
{
    for(;begin != end; ++begin)
    {
        std::cout << *begin << std::endl;
    }
}

用法:

std::vector<int> v = {1, 2, 3, 4};
printcontainer(v.cbegin(), v.cend());
相关文章: