std::string::npos的值是多少?有定义吗?

wesleyluo 2011-11-18 06:07:24
如题:
据说是大于所有有效下标的一个值,那这个值有定义是多少吗?

如果在程序中把-1作为它来用可以吗?
例如:

if(string.find() == -1)
{
cout <<"no found.";
}
...全文
2135 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 7 楼 xingfeng2510 的回复:
msdn中是这样定义的:static const size_type npos = -1;
没看到啊。
NeedBackup 2013-06-06
  • 打赏
  • 举报
回复
const typename basic_string<_Elem, _Traits, _Alloc>::size_type basic_string<_Elem, _Traits, _Alloc>::npos = (basic_string<_Elem, _Traits, _Alloc>::size_type)(-1);
xingfeng2510 2011-11-18
  • 打赏
  • 举报
回复
msdn中是这样定义的:static const size_type npos = -1;
hongwenjun 2011-11-18
  • 打赏
  • 举报
回复

// NB: This is an unsigned type, and thus represents the maximum
// size that the allocator can hold.
/// Value returned by various member functions when they fail.
static const size_type npos = static_cast<size_type>(-1);


自己右键 就可以查头文件
看头文件里的注解
//注:这是一个无符号的类型,是tring容易可容纳的最大大小。

xuyapeng1991 2011-11-18
  • 打赏
  • 举报
回复
我觉得还是直接用npos比较好。。
gwd8127 2011-11-18
  • 打赏
  • 举报
回复
不同的编译系统,NOPS的值是不同的,通常为-1。最好把它当作常量来使用。
taodm 2011-11-18
  • 打赏
  • 举报
回复
永远不要依赖于npos的实际值。
jixingzhong 2011-11-18
  • 打赏
  • 举报
回复
-1,但是完全没有必要直接和这个-1进行比较。
FrankHB1989 2011-11-18
  • 打赏
  • 举报
回复
ISO C++03
21.3
...
static const size_type npos = -1;
...
相当于static_cast<size_type>(-1)。应该注意这里的size_type是allocator决定的无符号数。
LZ这么做可以,不过还是写成npos明确一点。

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧