【发布时间】:2016-06-01 02:24:09
【问题描述】:
我在基于 Web 的编辑器中遇到此代码的分段错误,但在 XCode 中没有。我对这些错误不是很熟悉,但我查了一下并不能确定问题所在。另一个区别是我在使用 Web 编辑器时删除了 main 方法。有谁知道问题是什么?提前致谢。
#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;
}
【问题讨论】:
-
未定义行为的结果是未定义的。 (即,在遇到调用未定义行为的代码时,允许 XCode 崩溃,或不崩溃,或窃取您的立体声,或它选择做的任何其他事情)
标签: c++ vector segmentation-fault