这个函数有问题吧?

32131532 2007-08-15 05:40:48
#include<iostream>
#include<string>
#include<vector>
using namespace std;

typedef pair<short,short> location;
typedef vector<location> loc;
typedef vector<string> text;
typedef pair<text*,loc*> text_loc;

text_loc* separate_words(const vector<string> *text_file)
{
vector<string> *words=new vector<string>;
vector<location> *locations =new vector<location>;

short line_pos=0;

for(; line_pos < text_file->size(); ++line_pos)
{
short word_pos=0;
string textline=(*text_file)[line_pos];

string::size_type pos =0 ,prev_pos=0;

while(( pos=textline.find_first_of(' ',pos)) !=string::npos)
{
words->push_back( textline.substr(prev_pos, pos-prev_pos));

locations->push_back( make_pair(line_pos,word_pos));

++word_pos; prev_pos=++pos;
}

words->push_back( textline.substr(prev_pos,pos-prev_pos));

locations->push_back( make_pair(line_pos,word_pos));
}
return new text_loc(words,locations);
}

这里是不是有问题??
words->push_back( textline.substr(prev_pos,pos-prev_pos));

...全文
125 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
jxlczjp77 2007-08-15
  • 打赏
  • 举报
回复
楼上的说的没错,我原来碰到过这个问题,验证了一下
推出循环后pos=string::npos; pos-prev_pos确实是一个很大的整数
但是结果是正确的,应该是当大于字符串长度的时候,substr()默认取到字符串末尾
ouyh12345 2007-08-15
  • 打赏
  • 举报
回复
有可能。
注意substr里的参数是无符号的,如果pos-prev_pos小于0,则会转换成一个很大的整数。
如果prev_pos比pos-prev_pos大,也需要注意,具体结果可以做实验来验证。

64,636

社区成员

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

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