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

标签 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;
    }
}

最佳答案

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

相关文章:

c++ - 事件处理 : Sending events from base classes when the receiver expects derived classes

c++ - unique_ptr VS auto_ptr

c++ - 如何使用 SFINAE 为枚举类中的缺失值制作 polyfill?

c++ - 如何在不增加 vector 大小的情况下保留多维 vector ?

c++ - 在编译时确定 Eigen3 矩阵的存储顺序

c++ - 从库类扩展,然后如何让库调用派生类方法

c# - C++ 运算符重载

c++ - 一旦成为标准的一部分——boost 库会失去其 boost 命名空间并移至 std 吗?

c++ - 使用指针作为循环增量器而不是通常的 "int i"是个坏主意吗?

c++ - 以相反顺序打印数组,意外输出 (c++)