string :: npos的替代品

问题描述 投票:3回答:1

在自定义类的自定义find()方法返回自定义数据结构中元素的索引位置的情况下,是否有比返回string::npos更优雅的东西?

find()方法的返回类型是size_t。所以我需要它的类型size_t。

string::npos-1,这是unsigned long long的最大值。虽然这很有效,但我的问题是命名:string。我不想与string有任何联系。是否有任何内置更普遍的命名为这样的常见和一般情况,并与size_t兼容?

c++ c++11 c++14
1个回答
0
投票

如果您的自定义类想要从它的find函数返回size_t,那么只需定义您自己的size_t常量,供消费者引用为“未找到”。例如(伪代码,未验证编译):

class Foo
{
    public:
        static const size_t npos = static_cast<size_t>(-1);

        size_t find(/*thing to find here*/) const
        {
            // logic to search for element

            // element not found
            return(npos);
        }
};

然后消费者可以像std :: string一样使用它:

Foo foo;
size_t pos = foo.find(/*thing to find here*/);
if(pos != Foo::npos)
{
    // Element found
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.