c++ - std::find 与从 vector 导出模板

标签 c++ stl find

我在编程中经常使用 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/

相关文章:

c++ - 如何断言谷歌测试中的执行时间?

c++ - 我应该将我所有的 c++ 代码包装在它自己的命名空间中吗?

c++ - 为什么字符串 operator= 上的 double free?

c++ - 如何在 C++ 代码中包装 C 二维数组 (Foo**)?

c - execl() 查找命令 c

iphone - 数组,找到有值的对象并获取其indexPath

c++ - 如何在配置文件中隐藏数据库密码

c++ - 在方法之间传递值 C++

c++ - 获取给定对象的类型说明符

python - 有没有办法使 rfind() 不区分大小写?