【问题标题】:Out of range string?超出范围的字符串?
【发布时间】:2014-09-10 04:48:59
【问题描述】:

大家好,我遇到了 string.at(x) 超出范围的错误,我不知道为什么。任何帮助,基本上我试图确保我的对象字符串中的第一个字符不是 'z' 。另外我认为我的字符串比较可能无法正常工作,但如果我发现有重复的唯一单词,这可能与未完成的代码有更多关系。

struct wordCount{
string word;
int count;
}storeword[100];

void countWordFreq(wordCount compares[]){
int a=0;
unsigned i=0;
for(a;a<101;a++){
    cout<<"Length"<<compares[a].word.length();
    if(compares[a].word.at(i)<='z'||compares[a].word.at(i)>='A'){       
    compares[a].count++;
    }
    for(int b=1;b<101;b++){
        cout<<"Length"<<compares[b].word.length();
        if(compares[b].word.at(i)<='z'||compares[b].word.at(i)>='A'){           
        if(compares[a].word.compare(compares[b].word)==0){
            cout<<"true" << endl;
            compares[a].count++;
        }
    }
        b++;
    }
    a++;

}
for(int q;/*compare[q].word.at(0)<='z'||compare[q].word.at(0)>='A'*/q<10;q++){
    cout<<"Word: " << compares[q].word << " Count: " << compares[q].count << endl;
}

}

【问题讨论】:

  • 我猜compares 数组的大小是100。如果是这样,数组索引计数器ab 需要小于100,而不是小于101。当ab 的值为100 时,由于访问超出范围的内存,您将得到未定义的行为。

标签: c++ arrays string object


【解决方案1】:

哇。冒着听起来(是?——如果是的话,对不起)不礼貌的风险,我想我会以完全不同的方式做这项工作。

C++ 标准库提供了相当多的工具,可以更轻松地完成这项工作,并且很难找到错误等的机会要少得多。我会使用它们。

只是为了它的价值:我不确定我是否完全理解你描述的每个单词的第一个字符的比较。目前我假设您只想计算以字母开头的事物。不过,如果需要的话,很容易改变它。

#include <string>
#include <map>
#include <iostream>
#include <iomanip>
#include <cctype>
#include <sstream>

void countWordFreq(std::string const &input) {
    std::map<std::string, size_t> counts;

    std::istringstream buffer(input);

    std::string word;

    // read the words, count frequencies of those that start with letters
    while (buffer >> word)
        if (isalpha(word[0]))
            ++counts[word];

    // write out each word we found and how often it occurred:
    for (auto const &count : counts)
        std::cout << std::setw(20) << count.first << ": " << count.second << "\n";
}

就目前而言,这将按字母顺序打印出唯一的单词。如果您不需要这种排序,您可以(通常)通过使用std::unordered_map 而不是std::map 来提高速度。

【讨论】:

  • 谢谢,对不起,我还是编程新手,对所有库及其提供的内容以及正确使用它们都不是很熟悉。由于未声明地图,我无法运行它。
  • @user3051442:您需要包含&lt;map&gt; 才能获得声明。您还需要一些其他标题。我会编辑它们。
猜你喜欢
  • 2012-06-23
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 2016-05-18
  • 2013-05-13
相关资源
最近更新 更多