gpt4 book ai didi

c++ - std::string::size() const () 中的段错误?

转载 作者:行者123 更新时间:2023-11-30 02:09:33 26 4
gpt4 key购买 nike

我正在编写一个程序,告诉用户输入一个随机字符串,然后打印出所有重复项以及每个重复项的次数。我通过 gdb 运行它,这是输出:

程序如下:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
//Read a string word by word and put into a vector
//loop through the vector:
// If there are two words duplicate:
// loop through another vector (used to store duplicate word)
// compare if these two words are the same as the duplicate word stored
// If the same: ++count[i]
// If not: push_back(count) ; ++count[i]

string word;
vector<string> sentence;
vector<string> duplicate;
vector<int> times;
int count = 1;

while (cin >> word) {
if (word == "ctrlz") {
break;
}
sentence.push_back(word);
}

vector<string>::size_type i = 0;
vector<string>::size_type j = 0;

while (i != sentence.size()) {
if (sentence[i] == sentence[i+1]) {
while (j != sentence.size()) {
if (duplicate.size() == 0) {
duplicate.push_back(sentence[i]);
times.push_back(count);
++times[0];
}
else {
if (sentence[i] != duplicate[j]) {
duplicate.push_back(sentence[i]);
times.push_back(count);
++times[j+1];
}
else {
++times[j];
}
}
++j;
}
}
++i;
}

while (i != duplicate.size()) {
cout << duplicate[i] << ' ';
++i;
}

return 0;
}


运行 gdb 后我得到了这个:

(gdb) run 
Starting program: /home/phongcao/C++/6.12
phong phong phong phong phong phong
ctrlz

Program received signal SIGSEGV, Segmentation fault.
0x001c58d9 in std::string::size() const () from /usr/lib/libstdc++.so.6
(gdb)


这个输出是什么意思?我该如何解决这个段错误?

最佳答案

一些错误:

if (sentence[i] == sentence[i+1]) {

您的循环允许 i 为 size()-1 - 所以你读的是 vector 句末尾的内容。

while (i != sentence.size()) {
while (j != sentence.size()) {
...
++j;
}
++i;
}

j 永远不会重置 - 外循环的下一次迭代将从 sentence.size() 开始- 你可能不想要那样。

你应该用 std::map<std::string, int> 来解决这个问题:

std::map<std::string, int> words;
while (cin >> word) {
if (word == "ctrlz") {
break;
}
words[word] += 1;
}
for (std::map<std::string>::const_iterator it = words.begin(); it != words.end(); ++it) {
if (it->second > 1) {
cout << it->second << " copies of " << it->first << endl;
}
}

关于c++ - std::string::size() const () 中的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5306349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com