我在编程中经常使用 vector ,通常我使用 std::find 来遍历一个现有值的 vector ,如下所示:
std::vector<int> foo;
std::vector<int>::iterator pos( std::find( foo.begin(), foo.end(), bar );
这是一个真正的无聊。所以我从 std::vector 派生了一个模板来提供一个 find 方法:
template<class T>
class foovector : public std::vector<T>
{
public:
typename std::vector<T>::iterator find( const T& value )
{
return std::find( this->begin(), this->end(), value );
}
};
现在我可以更自然地进行查找了:
foovector<int> foo;
foovector<int>::iterator pos( foo.find( bar ) );
我的问题是,这似乎是 vector 的自然而明显的扩展,那么为什么它不是 STL 甚至 boost 的一部分?我觉得我在这里缺少一些奥术知识。
最佳答案
如果你做了你想实现的,但仍然没有走上从 std::vector 继承的可疑路径呢
定义一个独立函数
template <typename T>
typename std::vector<T>::const_iterator find( const std::vector<T>& v, const T& value )
{
return std::find( v.begin(), v.end(), value );
}
您可以将其放入命名空间 std(从技术上讲,这是不允许的),或放入其他命名空间(需要权衡的是 ADL 无法找到它,因此您需要对其进行限定)。
附言顺便说一下,您可以将其推广到所有容器
template <typename Container, typename T>
typename Container::const_iterator find( const Container& c, const T& value )
{
return std::find( c.begin(), c.end(), value );
}
关于c++ - std::find 与从 vector 导出模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3916568/