作者b6s (http://b6s.blogspot.com)
站内Programming
标题Re: 请问STL的string这样写有错误吗?
时间Thu Aug 17 23:55:22 2006
※ 引述《Killercat (杀人猫™)》之铭言:
: An input iterator addressing the first occurrence of the specified value in
: the range being searched. If no such value exists in the range, the iterator
: returned addresses the last position of the range, one past the final element.
: (这个基本上跟.end()的定义相同)
: 我比较不明白的是, .end()跟string::npos应该不会是一样的直吧 +_+
: 不过我似乎也有string::npos当传回值的印象...?
: 请问这大概是...?
抱歉,我没说清楚一件事。您在原程式码中用的和现在查到的这个是 <algorithm>
的 find(),我提到的则是 <string> 的 string::find(),
string::npos 是 ANSI C++ 规定的传回值,配合 string::size_type
针对 VC,请见
http://msdn2.microsoft.com/en-us/library/tbbk8hs6.aspx
当您把 string 当 container 操作它的 iterator 时,
string::end 照理说和 string::npos 的语意相通。
但是,重点来了,回圈里有 seq+=inl[i];
表示 string 当 container 时的 iterator 不再安全了,
换句话说,seq.end() 不再保证有如您预期的行为。
所以,我会建议改用 string::find() 和 string::npos
当然,最好是重新考虑用别的写法。
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.105.131.104
※ 编辑: b6s 来自: 59.105.131.104 (08/17 23:56)
※ 编辑: b6s 来自: 59.105.131.104 (08/17 23:57)
1F:推 Killercat:大致上明白了 非常感谢您解说/bow 218.163.161.9 08/18 00:24
2F:推 kafy:不懂,每次的end()不是都是重新呼叫的吗? 61.216.2.31 08/18 02:05
3F:推 kafy:我自己跑的结果是没问题的耶... 61.216.2.31 08/18 02:12
4F:推 cplusplus:每次都是在比较後才append到seq220.139.233.250 08/18 22:26
5F:→ cplusplus:每次也都是重新呼叫end 照理讲不会危险220.139.233.250 08/18 22:27
6F:→ cplusplus:如果重新呼叫有危险那这个lib应该烂掉了220.139.233.250 08/18 22:28
7F:推 b6s:请参考 Effective C++ 之类的书 59.105.131.104 08/19 02:15
8F:→ b6s:原 po 说在 VC7.1 有问题,mingw 没问题 59.105.131.104 08/19 02:16
9F:→ b6s:这种事其实不少见...... 59.105.131.104 08/19 02:16
10F:推 b6s:btw, Design Pattern 书里也有讲。 59.105.131.104 08/19 02:20
11F:推 cplusplus:所以vc 7.1 的lib可能烂了吗220.139.233.250 08/19 15:06
12F:推 cplusplus:请问在EFFECTIVE C++里哪个议题呢? 谢谢220.139.233.250 08/19 15:08
13F:→ cplusplus:但我还是绝得不该烂掉 不然就VC的烂掉了220.139.233.250 08/19 15:09
14F:推 cplusplus:刚刚测试在VC7.1跟8都没问题...220.139.233.250 08/19 15:14
15F:推 b6s:My bad, 是 exceptional C++ 59.105.131.104 08/23 19:09