2016-09-23 70 views
-1

我正试图解决这个problem。我写了这个代码:不能在我的代码中找到错误:C++

#include <iostream> 
#include <vector> 
using namespace std; 

int findIndex(x, lastAns, N) { 
    return ((x == !lastAns) % N); 
} 

void query_1(int x, int y, int N, int lastAns, std::vector< std::vector<int> >& v) { 

    v[findIndex(x, lastAns, N)].push_back(y); 

} 

void query_2(int x, int y, int N, int* lastAns, std::vector< std::vector<int> >& v) { 

    *lastAns = y % (v[findIndex(x, *lastAns, N)].size()); 
    cout << *lastAns << endl; 

} 

int main(int argc, char const *argv[]) 
{ 

    int N, Q; 
    cin >> N >> Q; 

    std::vector< std::vector<int> > v; 
    std::vector<int> buff; 
    int queryType; 
    int lastAns = 0; 
    int x, y; 

    for(int i=0; i<N; ++i) { 
     for(int j=0; j<N-1; ++i) { 
      buff.push_back(0); 
     } 

     v.push_back(buff); 

    } 

    for(int i=0; i<Q; ++i) { 
     cin >> queryType; 
     cin >> x >> y; 

     if(queryType == 1) { 
      query_1(x, y, N, lastAns, v); 
     } 

     else if (queryType == 2) { 
      query_2(x, y, N, &lastAns, v); 
     } 

     else continue; 
    } 

    return 0; 
} 

我得到的错误是:

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc

我还没有遇到过这种错误。当我通过gdb运行代码时,得到:

Program received signal SIGABRT, Aborted. 
0x00007ffff74ab418 in __GI_raise ([email protected]=6) 
    at ../sysdeps/unix/sysv/linux/raise.c:54 
54 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory. 

我的代码中存在什么问题?

+1

有人会建议你迟早使用debbuger ... – xinaiz

+1

有没有特别的原因使用丑陋的宏而不是普通或模板函数? – Slava

+0

没有理由。我只是想一个足够简单的计算,一个宏就足够了。 –

回答

3

注:

for(int i=0; i<N; ++i) { 
     for(int j=0; j<N-1; ++i) // <<<<<< some little mouse got here 

编辑:

说明: 您已经创建无限循环,其中j<N-1总是true。这意味着,您将新元素推入矢量中,直到没有更多内存可用,因此出现运行时错误。

+2

是的,回答“我的代码中有什么问题?” – xinaiz

+0

也许你应该更清楚一点? – Slava

+0

Yup删除了bad_alloc错误。感谢您的解释。 –

0

此函数可以是一个错误的原因:

int findIndex(x, lastAns, N) { 
    return ((x == !lastAns) % N); 
} 

首先,将参数丢失它们的类型。

接着,表达

!lastAns 

将evalute到零或非零。 这意味着您将整数x与零或非零进行比较: (x == 0) or (x == 1)
上述表达式的结果为零或非零。假设1为非零。你得到最终的表达

`return 0 % N;` or `return 1 % N`; 

最终的返回值是0或1。N变量并不重要,因为只有显著的值是0或1。你不能有N个零(你不检查),并且当n为1,你仍然可以得到0或1

所以,你的表达:

v[findIndex(x, lastAns, N)] 

v[0]或'v [1]。

+0

缺少的函数参数类型是对问题编辑不当的结果。这是一个宏观之前。 – xinaiz