[英]Segmentation Fault in C++ while using string vectors
My code is for an online coding practice site, I have been doing many of the challenges but I cannot seem to get around the segmentation fault error on this one.我的代码是用于在线编码练习网站的,我一直在做很多挑战,但我似乎无法解决这个问题上的分段错误错误。
The aim of the code is to find the longest length strings in a string vector (up to 10 strings long) and then to return a string vector containing just those longest strings in order.代码的目的是在字符串向量中找到最长的字符串(最多 10 个字符串),然后按顺序返回仅包含最长字符串的字符串向量。
I believe logically my code works, but I can't test it.我相信我的代码在逻辑上是有效的,但我无法测试它。 I am still new to vectors so can't seem to properly understand other answers on here in relation to my issue.
我对向量还是新手,所以似乎无法正确理解这里与我的问题有关的其他答案。
vector<string> allLongestStrings(vector<string> inputArray) {
vector<string> longestStrings; // vector
int longest_size = longestStrings.size(); // int
int longestArrayCounter = 0; // int. For filling longestStrings whenever
// there is a long string
int longest_string = 0; // int. For recording the size of the longest string
for (int i = 0; i < inputArray.size(); i++) {
// Loop will:
//1. Measure size of string in input array
//2. if longest will change value of longest_string and clear longestStrings
//3. If the same length as longest_string will add it to longestStrings vector
//4. if it is shorter it will be ignored
if (inputArray[i].size() > longest_string) { // input vector
longest_string = inputArray[i].size(); // vector
longestStrings.clear(); //clearing the vector to only store longest string values
longestArrayCounter = 0; //reset counter for longestStrings
longestStrings[longestArrayCounter++] = inputArray[i];//puts new longest string from input into my vector
}
if (inputArray[i].size() == longest_string) {
longestStrings[longestArrayCounter++] =inputArray[i];// my vector and input vector
}
}
return longestStrings;
}
longestStrings.clear();
longestArrayCounter = 0;
longestStrings[longestArrayCounter++] = inputArray[i];
is bad because you are doing assignment to non-existent element.不好,因为您正在对不存在的元素进行分配。
Instead of the two而不是这两个
longestStrings[longestArrayCounter++] = inputArray[i];
you should do你应该做
longestStrings.push_back(inputArray[i]);
Then, std::vector
will manage the size for you, so you don't have to manage longestArrayCounter
by yourself.然后,
std::vector
将为您管理大小,因此您不必自己管理longestArrayCounter
。 Use longestStrings.size()
to obtain the size.使用
longestStrings.size()
获取大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.