STL算法将整个容器而不是.begin(), end()作为参数

STL algorithms taking the whole container rather than .begin(), end() as arg?

本文关键字:begin end 参数 算法 STL      更新时间:2023-10-16

独立的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算法是通过迭代器与容器连接/对话的。