gpt4 book ai didi

c++ - XCode 中忽略了段错误

转载 作者:行者123 更新时间:2023-11-28 02:05:53 25 4
gpt4 key购买 nike

我在基于 Web 的编辑器中遇到此代码的段错误,但在 XCode 中却没有。我对这些错误不是很熟悉,但我查了查并无法确定问题所在。另一个区别是我在使用 Web 编辑器时删除了主要方法。有谁知道问题出在哪里?提前致谢。

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;

class Lexer
{
public: vector <string> tokenize(vector <string> tokens, string input);
};

vector <string> Lexer::tokenize(vector <string> tokens, string input)
{
vector <string> consumed;

if(tokens.size()>50)
{
tokens.resize(50);
}

//The next section sorts the tokens from largest to smallest

int swap_count = 0; //this tracks whether the sort needs to happen again

do
{
swap_count = 0; // set the swap count to zero

for(int i=0; i<tokens.size(); i++) //loop that runs the length of the 'tokens' string
{
if(tokens[i].length()<tokens[i+1].length()) // if this token is smaller in length than the next token
{
tokens[i].swap(tokens[i+1]); //swap the tokens
swap_count++; //add one to the swap count
}
}
}
while(swap_count!=0); //while there are swaps

//The next section consumes the input string.
while(input.length()>0)
{
int count_tokens_consumed=0;

for(int i=0; i<tokens.size(); i++) // loop set up to go through the units in the tokens vector
{
if(tokens[i]==input.substr(0,tokens[i].length())) //if the current token matches the first part of the input
{
consumed.push_back(tokens[i]); //add the token to the consumed vector
input = input.substr(tokens[i].length()); //remove the token from the front of the input string
count_tokens_consumed++;
i=int(tokens.size());
}
}

if (count_tokens_consumed==0)
{
input = input.substr(1);//or remove the first character on no match
}
}

return consumed;
}

int main()
{
Lexer LexerOne;
vector <string> LexerOne_out = LexerOne.tokenize({"AbCd","dEfG","GhIj"},"abCdEfGhIjAbCdEfGhIj");
for(vector<string>::iterator i = LexerOne_out.begin(); i != LexerOne_out.end(); ++i)

cout << *i << " ";
return 0;
}

最佳答案

段错误是否在一种环境中被忽略,而在另一种环境中是否被忽略是无关紧要的。
导致段错误的操作是未定义的行为。


下面一行代码:

line 31: tokens[i+1].length()

不是您的 token 的有效索引。
这是因为您正在从 0 迭代到 tokens.size()
token 的有效索引范围是从 0 到 tokens.size()-1

关于c++ - XCode 中忽略了段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37558426/

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