【问题标题】:Segmentation fault looking for longest strings in a vector [closed]在向量中寻找最长字符串的分段错误[关闭]
【发布时间】:2022-01-07 21:30:21
【问题描述】:
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;
}

如果有帮助,这就是问题

给定一个字符串数组,返回另一个包含所有最长字符串的数组。

例子

对于 inputArray = ["aba", "aa", "ad", "vcd", "aba"],输出应该是

solution(inputArray) = ["aba", "vcd", "aba"].

【问题讨论】:

  • iasol 向量中有多少个字符串? (零。没有。)
  • 在您的第二个循环中,您正在索引一个空向量。你不能这样做来插入,你只能这样做来访问一个 alrady-existing 元素。而不是iasol[i]=ia[i];iasol.push_back(ia[i]);
  • 另外,这可以通过单次遍历数据来解决。
  • [] 的用法更改为at()。然后你不会得到分段错误,但你会得到一个std::out_of_range 异常抛出,告诉你你做错了什么。
  • Here is an example。只需在正确的位置使用at() 即可确定问题。答案部分给出了解决问题的方法。

标签: c++ string algorithm vector function-definition


【解决方案1】:

问题在于iasol 最初是空的,因此使用iany 值对其进行索引将超出范围。 std::vector 会在您向其添加元素时增长。而不是 iasol[i] = ia[i]; 在您的第二个循环中,执行 iasol.push_back(ia[i]); 将其添加到结果中。 live example

我还建议使用 ranged-for 而不是基于索引来使这一点更清晰。

std::vector<std::string> solution(const std::vector<std::string>& input) {
  std::size_t max_size{};
  for (const auto& s : input) {
    auto sz = s.size();
    if (sz > max_size) {
      max_size = sz;
    }
  }
  
  std::vector<std::string> longest_strings;
  for (const auto& s : input) {
    if (s.size() == max_size) {
      longest_strings.push_back(s);
    }
  }
  return longest_strings;
}

live link

【讨论】:

    【解决方案2】:

    声明为like的向量

    vector<string> iasol;
    

    没有元素。所以这个说法

    iasol[i] = ia[i];
    

    调用未定义的行为。

    您需要应用两种标准算法std::max_elementstd::copy_if

    这是一个演示程序。

    #include <iostream>
    #include <string>
    #include <vector>
    #include <iterator>
    #include <algorithm>
    
    std::vector<std::string> solution( const std::vector<std::string> &v )
    {
        auto it = std::max_element( std::begin( v ), std::end( v ),
            []( const auto &s1, const auto &s2 )
            {
                return s1.size() < s2.size();
            } );
    
        auto n = it->size();
    
        std::vector<std::string> result;
    
        std::copy_if( std::begin( v ), std::end( v ), std::back_inserter( result ),
            [&n]( const auto &s ) 
            { 
                return s.size() == n; 
            } );
    
        return result;
    }
    
    
    int main()
    {
        std::vector<std::string> v = { "aba", "aa", "ad", "vcd", "aba" };
    
        auto result = solution( v );
    
        for (const auto &s : result)
        {
            std::cout << s << ' ';
        }
    
        std::cout << '\n';
    }
    

    程序输出是

    aba vcd aba
    

    【讨论】:

      【解决方案3】:

      由于我发现你开发的源代码可读性低,我针对这个问题开发了一个新的解决方案。

      #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 << ' ';
      }
      

      此程序产生以下输出:

      aba vcd aba
      

      【讨论】:

      • “答案”不能说明 OP 做错了什么并导致分段错误。
      • 附加说明。不建议使用using namespace std;getMaximumSizeprintgetElementBySize 创建输入向量的副本,这对于较小的向量不是问题,但不是一个好方法。
      • 我不想额外说明,因为有人说问题出在哪里;它需要使用push_back() 方法将元素添加到向量容器中。
      • See this。当然会占用更多空间。
      • 当然可以,但答案应该不言自明。谁保证其他答案不会被删除(或更改),或者其他答案将添加不正确的解释。
      猜你喜欢
      • 2022-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 2017-02-02
      • 2021-03-23
      • 1970-01-01
      相关资源
      最近更新 更多