gpt4 book ai didi

c++ - 替代字符串::npos

转载 作者:太空狗 更新时间:2023-10-29 23:11:48 31 4
gpt4 key购买 nike

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

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

string::npos-1,即unsigned long long的最大值。虽然这很好用,但我的问题是命名:string。我不希望与 string 有任何关联。是否有针对这种常见和一般场景更普遍命名并与 size_t 兼容的内置内容?

最佳答案

如果您的自定义类想要从它的查找函数返回一个 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
}

关于c++ - 替代字符串::npos,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216037/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com