c++ - 当我添加语句时,C++ 中的结果输出错误

标签 c++ cout endl

我尝试使用 3 * (n // 2) 查找数组(大小为 n)中的最小值和最大值一次遍历的次数比较。这是我的代码:

#include <iostream>
#include <initializer_list>
//!
//! @Brief:get the minmum and maxmum in 3 * ( n // 2) times comparison.
//! Create by Soyn. 31/7/15.
//!

    bool IsOdd( size_t n)
    {
        return n % 2 ;
    }
    std::initializer_list<int> getLargerAndSmaller( int a, int b)
    {
        if(a <= b){
            return {a,b};
        }else{
            return {b,a};
        }
    }

    int main(void)
    {
        int  Min, Max;
        int a[] = {5,4,1,7,3,8,3,4,9,10};
        int n = sizeof(a) / sizeof(a[0]);
        for( int i = 0; i < n - 1; i += 2){
            if( (i ==0) &&IsOdd(n)){           // initialize the Min and Max.
                Min = Max = a[i];
            } else{
                    auto item = getLargerAndSmaller(a[i],a[i+1]);
                    if(i == 0){
                            Min = *(item.begin());
                            Max = *(item.begin() + 1);
                            std :: cout << "Min: " << Min << " , " << "Max: " << Max << std :: endl;
                        }else{
                        std :: cout << *(item.begin()) << " , " << *( item.begin() + 1) << std :: endl;
                        Min > *(item.begin()) ? Min = *(item.begin()) : Min;
                        Max < *(item.begin() + 1) ? Max = *(item.begin() + 1) : Max;
                        std :: cout << "Min: " << Min << " , " << "Max: " << Max << std :: endl;
                        }
            }
        }
         return 0;
    }

为了测试我的代码,我在代码中添加了一些语句,例如

std :: cout << *(item.begin()) << " , " << *( item.begin() + 1) << std :: endl;

这是我无法弄清楚的一点。当我添加这个时,结果是错误的。如果我清除它,效果很好。以下是错误的结果图片:

enter image description here

最佳答案

函数返回 std::initializer_list 几乎永远不会正确,因为它们引用本地数组。

当您编写 return {a, b}; 或等效的说明时:

std::initializer_list<int> x = { a, b };
return x;

所发生的情况是,创建了一个由 2 个元素组成的自动(堆栈)数组,其中包含 ab 的拷贝; initializer_list 对象保存对该本地数组的引用。

因此,当您访问 item 时,您正在访问悬空引用(未定义的行为)。


initializer_list 并非设计用作容器 - 使用 arrayvectorpair 等. 相反。

关于c++ - 当我添加语句时,C++ 中的结果输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31738026/

相关文章:

C++ 如果在函数中不起作用

c++ - Windows TPM 虚拟智能卡 RSA key 存储

c++ - 如果没有 std::flush 则发生段错误

c++ - Windows 图形用户界面 : Can I access the "modern ui" from C++?

c++ - 计算前缀和

c++ - std::cout 的更易于键入的替代方案,用于在 C++ 中打印到屏幕

c++ - cout 在对象实例化后不输出

c++ - stdout 除了控制台窗口之外还有其他东西吗?

c++ - 换行符是否也刷新缓冲区?

c++ - 如何重载 std::cout << std::endl?