min()函数的副作用

时间:2014-03-13 21:20:24

标签: c++ c++11

我不明白为什么a [i]的价值被无意中修改了?注释标记的行应该只修改数组p的值而不是a的值。我注意到数组的值被修改为副作用。我无法弄清楚原因。

#include <iostream>
#include <unordered_map>

using namespace std;

int main() {
    unsigned int N, Q, K;
    unsigned int a[N], p[N][N];
    unordered_map<unsigned int, unsigned int> counts_vector;
    cin >> N;
    for (unsigned int i = 0; i < N; i++) {
        cin >> a[i];
        p[i][i] = a[i];
        for (unsigned int j = 0; j < i; j++) {
            p[j][i] = min(p[j][i - 1], a[i]); // why is the value of a[i] getting modified?
        }
    }
    for (unsigned int k = 0; k < N; k++) {
        cout << "a: "<<a[k]<< endl;
    }
}

1 个答案:

答案 0 :(得分:2)

在N被赋予值之前,你不应该声明unsigned int a[N], p[N][N];

更改

unsigned int N, Q, K;
unsigned int a[N], p[N][N];
unordered_map<unsigned int, unsigned int> counts_vector;
cin >> N;

unsigned int N, Q, K;
cin >> N;
unsigned int a[N], p[N][N];
unordered_map<unsigned int, unsigned int> counts_vector;