将std容器传递给函数
Pass a std container to a function
我提出了以下内容:
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::begin
和std::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());
相关文章:
- 无法引用该函数" std:: variant <_Types...> operator =",因为此函数已被删除
- 错误:使用已删除的函数"std::unique_ptr<...>
- 我有模板功能.通过使用函数std::for_each,用这个容器中的最大数字替换每个正数
- 如何使用函数std::min()来计算最小值
- 删除了 g++ 在 linux 中basic_stringstream函数 std
- 如何在 c++ 中使用返回类型导出函数 std::map
- 错误:使用已删除的函数"std::atomic<_Tp>::atomic() [_Tp = node]"
- 使用 SFINAE 检查函数 std::to_string 是否存在类型
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 为什么函数 std::basic_streambuf::setg() 需要非常量 agruments
- C++将已删除的函数 std::unique_ptr 与基类一起使用
- 奇怪的错误:当没有真正创建指针时,使用已删除的函数'std::unique_ptr<_Tp,_Dp>::unique_ptr
- 通过模板构造函数(std ::功能和迷你案例)将构造函数触发
- 错误:使用已删除的函数"std::atomic<_Tp>::atomic()
- 错误:使用已删除的函数std::basic_ofstream(OpenCV和C++11)
- 类成员容器迭代器在成员函数std::find中不兼容,但为什么不兼容呢
- 没有构造函数 std::istream_iterator 的实例
- 错误:没有与参数列表匹配的重载函数"std::make_shared"实例
- 错误:使用已删除的函数"std::thread::thread(const std::thread&)"
- 不能在没有对象的情况下调用成员函数 std::string class::function()