2015-07-28 38 views
-4

我正在根据素数生成来解决这个简单的problem。在Xcode中,它运行成功。但是,当我提交解决方案到SPOJ它说runtime error SIGSEGV。我在网上搜索了什么是这个运行时错误,当我检查我的解决方案时,我没有看到任何问题。 所以如果在我的代码中有什么问题,它是什么,它如何解决?SPOJ中的运行时错误(SIGSEGV)

#include <iostream> 
#include <list> 
using std::cout; 
using std::cin; 
using std::endl; 

int main() { 
    int tcases = 0; 
    cin >> tcases; 
    const int ccase = tcases; 
    tcases = 0; 

    while (tcases != ccase) { 
    int m = 0, n = 0; 
    cin >> m >> n; 
    std::list<int> p; 
    int i = 0; 
    if (m == 1) i = ++m; 
    if (m > 1) i = m; 
    for (; i <= n; p.push_back(i), ++i); 
    // get all the elements 
    for (auto first = p.begin(), last = p.end(); first != last; ++first) { 
     if (*first == 2) continue; 
     else if (*first == 3) continue; 
     else if (*first == 5) continue; 
     else if (*first == 7) continue; 
     else if (*first % 2 == 0) p.erase(first); 
     else if (*first % 3 == 0) p.erase(first); 
     else if (*first % 5 == 0) p.erase(first); 
     else if (*first % 7 == 0) p.erase(first); 
    } 
    for (auto &elem: p) 
     cout << elem << endl; 

    cout << endl; 
    ++tcases; 
    } 
    return 0; 
} 

回答

0

当你说的问题是,

p.erase(first); 

擦除删除当前元素,并返回一个迭代器列表中的下一个元素,你是不是在你的代码的任何地方储存。而你在你的for循环,所以当下次循环运行递增firstfirst is not pointing to a valid location and hence the runtime error.

更改for loop到以下

for (auto first = p.begin(), last = p.end(); first != last;) { 
      if (*first == 2) 
      { 

       first++; 
       continue; 
      } 
      else if (*first == 3) 
      { 

       first++; 
       continue; 
      } 
      else if (*first == 5) 
      { 

       first++; 
       continue; 
      } 
      else if (*first == 7) 
      { 
       first++; 
       continue; 
      } 
      else if (*first % 2 == 0) 
       first = p.erase(first); 
      else if (*first % 3 == 0) 
      first = p.erase(first); 
      else if (*first % 5 == 0) 
      first = p.erase(first); 
      else if (*first % 7 == 0) 
       first = p.erase(first); 
      else 
       first++; 
     } 

附: :共享代码只是为了展示如何使用擦除。

+0

不起作用。这次显示错误的答案。 –

+0

虽然适合我,但用不同的输入测试过,看看你是否正确地改变了它。然而,你的问题是你用错误的方式擦除。 – Nishant

+0

在我的系统上,它应该可以正常工作。但是,当我提交它显示错误的答案。 –