Search code examples
c++stringalgorithmvectorfunction-definition

Segmentation fault looking for longest strings in a vector


Given an array of strings, return another array containing all of its longest strings. The solution I developed is available below:

#include <iostream>
#include <vector>

using namespace std;

vector<string> solution(vector<string> ia) {
  int maxi = -1;
  int size = ia.size();
  vector<string> iasol;

  for (int i = 0; i < size; i++) {
    int m = ia[i].length();
    cout << m << " " << maxi << endl;
  
    if (m > maxi)
      maxi = m;
  }

  for (int i = 0; i < size; i++) {
    int m = ia[i].length();
  
    if (m == maxi) {
      iasol[i] = ia[i];
      cout << iasol[i];
    }
  }
  return iasol;
}

int main() {
    vector<string> inputArray = {"aba", "aa", "ad", "vcd", "aba"};
    solution(inputArray);
}

The program is expected to work as follows:

INPUT
inputArray ← ["aba", "aa", "ad", "vcd", "aba"]

OUTPUT
solution(inputArray) → ["aba", "vcd", "aba"]

The above solution gives the following error:

3 -1
2 3
2 3
3 3
3 3
Segmentation fault

How do I solve this problem?


Solution

  • Since I found the readability of the source code you developed low, I developed a new solution for this problem.

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    /* Returns the size of the vector with the maximum length. */
    size_t getMaximumSize(vector<string> input);
    
    /* Returns a vector container based on the string length. */
    vector<string> getElementBySize(vector<string> input, size_t size);
    
    /* Prints the vector container. */
    void print(vector<string> input);
    
    int main()
    {
        vector<string> input{"aba", "aa", "ad", "vcd", "aba"};
        print(getElementBySize(input, getMaximumSize(input)));
        return 0;
    }
    
    vector<string> getElementBySize(vector<string> input, size_t size)
    {
        vector<string> result;
        
        for(int i = 0 ; i < input.size(); ++i)
            if(input[i].size() == size)
                result.push_back(input[i]);
                
        return result;
    }
    
    size_t getMaximumSize(vector<string> input)
    {
        size_t maximumNumberOfCharacters = input[0].size();
    
        for(int i = 0 ; i < input.size() - 1 ; ++i)
            if(input[i].size() < input[i+1].size())
                maximumNumberOfCharacters = input[i+1].size();
        
        return maximumNumberOfCharacters;
    }
    
    void print(vector<string> input)
    {
        for(string i : input)
            cout << i << ' ';
    }
    

    This program produces the following output:

    aba vcd aba