指向指针2-d数组的指针迭代

时间:2017-07-31 08:50:27

标签: c++ arrays pointers dynamic-arrays

我在Hackerrank上做了这个挑战,我尝试了所有我能做但却没有做到的。 挑战细节是:https://www.hackerrank.com/challenges/dynamic-array/problem

我的代码是:

 #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int noOfSequence, noOfQuery;
    int lastAnswer = 0, j=0;
    int query, x, y;

    cin>>noOfSequence>>noOfQuery;

    int *seqLength = new int[noOfSequence];
    for(int i=0; i<noOfSequence; i++){
        seqLength[i] = 0;
    }

    int **seqList = new int*[noOfSequence];
    for(int i=0; i<noOfSequence; i++){
        seqList[i] = new int [noOfSequence];
    }

    for(int i=0; i<noOfQuery; i++){
        cin>>query>>x>>y;
        switch(query){
            case 1: {
                        int seqListIndex = (x ^ lastAnswer) % noOfSequence;
                        *(seqList[seqListIndex] ++) = y;
                        seqLength[seqListIndex] += 1;
                        break;
                    }
            case 2: {
                        int seqListIndex = (x ^ lastAnswer) % noOfSequence;
                        lastAnswer = seqList[seqListIndex][y%seqLength[seqListIndex]];
                        cout<<lastAnswer;
                        break;
                    }
            default: cout<<"default"<<endl;
        }
    }

    return 0;
}

1。 int **seqList是指向指针数组的指针。指针数组进一步指向int的各个数组。

2. int *seqLength是指向整数数组的指针。这个整数数组跟踪上面提到的数组的长度。 3。int seqListIndex表示指针数组的索引。

我猜计算lastAnswer的方式有问题。我已经尽可能地检查了它,但仍然无法找到任何东西。 我也试图理解我们如何迭代int数组但是更多的知识会很棒。

1 个答案:

答案 0 :(得分:0)

问题在于您将seqList[seqListIndex]视为指向&#34; next元素&#34;的指针,但y%seqLength[seqListIndex]是与其原始值的偏移量。

&#34; next元素的索引&#34;是seqLength[seqListIndex],所以请替换

*(seqList[seqListIndex] ++) = y;

seqList[seqListIndex][seqLength[seqListIndex]] = y;

(如果您使用std::vector,您的代码可能会大大简化。)