[Solved] C++ vector matching [closed]


You code has undefined behavior because you are accessing them beyond the size. In v1 there will be 7 items, while in v2, there will be 3. But you are accessing both upto index 20. So the output can be anything.

To avoid this, you can resize your vectors and then assign 1 to specified indexes.

v1.resize(N); // keep enough space
v2.resize(N);


for(int i = 0; i < N; i+=3) {
 v1[i]=1;
}
for(int i = 0; i < N; i+=7) {
 v2[i]=1;
}
for(int i = 0; i < N; ++i) {
 if(v1[i] == 1 && v2[i] == 1) count++;
}

Another problem is your loop conditions are i<=N, which should be i<N. vector has zero based index.

0

solved C++ vector matching [closed]