salander_lisbeth salander_lisbeth - 9 months ago 43
C++ Question

Cant find error in my code : C++

I am trying to solve this problem. I have written this code:

#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) {



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;

The error I get is :

terminate called after throwing an instance of 'std::bad_alloc'

what(): std::bad_alloc

I havent come across this error before. When I run the code through gdb, I get this :

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

What is the problem in my code?



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


Explanation: You have created infinite loop, where j<N-1 is always true. This means, you push new elements into vector until no more memory is available, hence the run-time error.