简体   繁体   English

为什么此Vector下标超出范围?

[英]Why is this Vector subscript out of range?

Yes I am learning vectors currently. 是的,我目前正在学习向量。 I am trying to read in a text file, count the number of unique words, and then output a text file(will do later). 我试图读取一个文本文件,计算唯一单词的数量,然后输出一个文本文件(稍后再做)。 Could use some assistance in grasping what is going on and why/how to fix? 可以使用一些帮助来掌握正在发生的事情以及为什么/如何解决吗?

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include<vector>
using namespace std;
string toLower(string str);
string eraseNonAlpha(string Ast);
string  wordWasher(string str);
int countUniqenum(vector<string>&v);
int main()
{   
    ifstream inputStream; //the input file stream
    string word; //a word read in from the file
    string words=wordWasher(word);
    inputStream.open("alpha.txt");
    if (inputStream.fail())
    {
        cout<<"Can't find or open file"<<endl;
        cout<<"UR a loser"<<endl;
        system("pause");
        return 0;
    }//end if

    while (!inputStream.eof())
    {
        inputStream>>words;

    }//end loop

    vector<string> v;
    v.push_back(words);
    int unique =countUniqenum(v);
    cout<<unique<<endl;
    inputStream.close();

system("pause");
return 0;

}

string toLower(string str)
{

       for(int i=0;i<str.length();i++)
       {
               if (str[i]>='A'&& str[i]<='Z')
                 str[i]=str[i]+32;
       }
     return str;
}
string eraseNonAlpha(string str)
{
    for(int i=0;i<str.length();i++)
    {
        if(!((str[i]>='A'&&str[i]<='Z')||(str[i]>='a'&&str[i]<='z'))) 
        {str.erase(i,1);
        i--;
    }   
    }
    return str;
}

string  wordWasher(string str)
{   str=eraseNonAlpha(str);
    str=toLower(str);
    return str;
}                               
int countUniqenum(vector<string>&v)
{ int count=0;
  for(int i=0;i<v.size();i++)
  {
          if(v[i]!=v[i+1])
          count++;
  }     
  return count;
}  

You are definitely going beyond bounds here: 您肯定在这里超越了界限:

for(int i=0;i<v.size();i++)
{
      if(v[i]!=v[i+1])
//               ^^^

There may well be other errors. 可能还有其他错误。

It's the line if(v[i]!=v[i+1]) . 这行是if(v[i]!=v[i+1]) On your last trip through the loop, v[i] is the last element of the vector and v[i+1] is off the end. 在循环的最后一次行程中, v[i]是向量的最后一个元素,而v[i+1]不在终点。

A simple fix is to change the loop to for(int i = 0; i < v.size() - 1; i++) . 一个简单的解决方法是将循环更改为for(int i = 0; i < v.size() - 1; i++) I'm not sure that function really does what you want it to do, but that'll at leaset get rid of the crash. 我不确定该函数是否确实可以实现您想要的功能,但这至少可以消除崩溃。

您不应该对向量进行排序以使其工作..您只是在检查相邻单词是否相同

if(v[i]!=v[i+1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM