c++primer习题6.12 程序死掉 求助
/***********************************************
时间:2013-7-31
题目:
编写一个小程序,从标准输入读入一系列string对象,寻找连续重复出现的单词。
程序应该找出满足以下条件的单词的输入位置:该单词的后面紧跟着再次出现自己本身,
跟 踪重复次数量多的单词及其重复次数.
输出重复次数的最大值,
例如.如果输入是:
how now now now brown cow cow
则输出表明now这个单词出现了三次
**************************************************/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int find_max(vector<int>ivec);
int main()
{
vector<string> svec;
vector<int> ivec; //保存重复单词出现的次数
vector<string>::iterator iter;
vector<int>::size_type ix = 0;
string s;
int s_ct = 0; //相同单词的数目
bool flag = true; //标记相等的单词
cout << "enter string:(ctrl+z to quit)" << endl;
while(cin >> s)
svec.push_back(s);
iter = svec.begin();
while(iter != svec.end())
{
flag = true;
if((*iter == *(iter + 1)) && flag) //越界问题
{
flag = true;
s_ct++;
}
else
{
flag = false;
ivec[ix++] = s_ct + 1; //?
s_ct = 0;
}
iter++;
}
int x=find_max(ivec);
cout << "重复次数最多的单词的次数:" << x << endl;
return 0;
}
int find_max(vector<int>ivec)
{
vector<int>::size_type ix = 0;
int max_ct = ivec[0];
for(ix = 1; ix != ivec.size(); ++ix)
if(ivec[ix] > max_ct)
max_ct = ivec[ix];
return max_ct;
}
return 0;
}
void find_max(vector<int>ivec, vector<string> svec)
{
vector<int>::size_type ix = 0;
int max_ct = ivec[0], max_index = 0;
for(ix = 1; ix != ivec.size(); ++ix)
if(ivec[ix] > max_ct)
{
max_ct = ivec[ix];
max_index = ix;
}
cout << "重复次数最多的单词和次数:" << svec[max_index]
<< ":" << max_ct << endl;
}
已经在VS2008下面测试过了,没出现问题。
[解决办法]
崩溃的时候在弹出的对话框按相应按钮进入调试,按Alt+7键查看Call Stack里面从上到下列出的对应从里层到外层的函数调用历史。双击某一行可将光标定位到此次调用的源代码或汇编指令处。
判断是否越界访问,可以在数组的最后一个元素之后对应的地址处设置数据读写断点。如果该地址对应其它变量干扰判断,可将数组多声明一个元素,并设置数据读写断点在该多出元素对应的地址上。
#include <time.h>
#include <stdlib.h>
#include <windows.h>
int main() {
int a,b[11];//本来是b[10],为判断哪句越界,故意声明为b[11]
srand((unsigned int)time(NULL));//按两次F11,等黄色右箭头指向本行时,调试、新建断点、新建数据断点,地址:&b[10],字节计数:4,确定。
while (1) {//按F5,会停在下面某句,此时a的值为10,b[10]已经被修改为对应0..4之一。
b[(a=rand()%11)]=0;
Sleep(100);
b[(a=rand()%11)]=1;
Sleep(100);
b[(a=rand()%11)]=2;
Sleep(100);
b[(a=rand()%11)]=3;
Sleep(100);
b[(a=rand()%11)]=4;
Sleep(100);
}
return 0;
}