gpt4 book ai didi

c++ - min() 函数的副作用

转载 作者:行者123 更新时间:2023-11-28 02:54:08 26 4
gpt4 key购买 nike

我不明白为什么 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;
}
}

最佳答案

你不应该在 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;

关于c++ - min() 函数的副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22391165/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com