STL算法将整个容器而不是.begin(), end()作为参数
STL algorithms taking the whole container rather than .begin(), end() as arg?
独立的STL算法(如std::count_if
)使用一对迭代器。在我使用它们的所有情况下(以及我在网上看到的所有示例!),我发现自己键入
std::count_if(myContainer.begin(),myContainer.end(), /* ... */ );
样式为
的简写模板有什么原因吗?std::count_if(myContainer, /* ... */ );
如果在整个容器上执行的操作多于不提供,则不提供
。是我忽略了吗?c++11和c++03的答案不同吗?
Herb Sutter有一篇很好的博客文章讨论了这个问题。要点是,如果已经存在具有相同数量模板参数的算法的重载,则为算法添加基于容器的重载可能会产生歧义。概念是用来解决这个问题的
STL的原理和灵活性主要是因为操作的是迭代器而不是容器。这不是一个大问题,你可以重复使用我早年使用的技巧:
#define FULL_RANGE(c) (c).begin(), (c).end()
std::copy(FULL_RANGE(c), std::ostream_iterator<c::value_type>(cout, "n"));
的一个原因可能是为迭代器范围提供的灵活性。有时可能不需要遍历所有元素:
<iterator> it = myContainer.begin();
it++; // do something
it++; // do something
...
std::count_if(it, myContainer.end(), /* ... */ );
同样,你也可以有一个包装器来为你做这些:
template<typename T>
... count_if (T myContainer, ...)
{
std::count_if(myContainer.begin(), myContainer.end(), /* ... */ );
}
原因很简单,因为STL算法是通过迭代器与容器连接/对话的。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- remove(str.begin(), str.end(), );无法正常工作(我正在使用视觉工作室 2012)
- 了解向量中的 .begin 和 .end
- C++ const char with .begin() and .end()
- 为什么 std::find( s.begin(), s.end(), val ) 比集合 s 的 s.find(val) 慢 1000 倍<int>?
- 如何使用vector.begin()和vector.end()遍历矩阵?
- 如何实现 cbegin() 和 cend() 从 begin() 和 end() ?
- C++ - 空的 std::list begin() 和 end() 不相等
- 为什么std::begin()和std::end()适用于固定数组,而不适用于动态数组
- C++代码"x.erase(std::remove(x.begin(), x.end(), ), x.end())"是如何工作的?
- begin(),end()和cbegin(),cend()之间的区别是什么?
- 在模板化数据结构上调用 begin() 或 end()
- 重载 std::begin() 和 std::end() 用于非数组
- 使用 std::set 的 .begin() 和 .end() 函数会产生意想不到的结果
- 使用范围V3视图来实现begin()/end()方法
- 为 C++ 选择 begin() 和 end()
- 为什么"begin/end"与"first/last"的差异?
- Empty std::vector begin != end
- 匹配可迭代类型(具有begin()/end()的数组和类)