c++ - 寻找 vector 中的最小数

标签 c++

我正在尝试获取 vector 中的最小数字,但我的代码每次运行时都输出 000。

我已经尝试查看有关堆栈溢出的其他问题,但似乎其他人没有收到与我类似的错误。

    cout << "The smallest number is: ";
    for (i = 0; i < numberList.size(); ++i) {
        int smallest = numberList.at(0);
        if (numberList.at(i) < smallest) {
            smallest = numberList.at(i);
            }
        cout << smallest;
        }

当我输入 3 个数字时:1 2 3(作为单独的输入) 我知道最小的数字是:000

最佳答案

您在循环内声明最小值并输出,因此它会在每次迭代时执行此操作,现在开始:

std::cout << "The smallest number is: ";
int smallest = numberList.at(0);
for (int i = 0; i < numberList.size(); ++i) {

    if (numberList.at(i) < smallest) {
        smallest = numberList.at(i);
    }

}
std::cout << smallest;

如果你得到“0”,你的 vector 可能在某处有 0。但是您需要发布为此创建它的方式。

此外,您也可以只使用 numberList[i],不需要 .at()。

关于c++ - 寻找 vector 中的最小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58533308/

相关文章:

c++ - 循环中标量积的自动矢量化

c++ - 从函数调用返回后,来自 std::vector 引用的数据损坏

c++ - QMutex 访问共享变量

c++ - 在模块(exes和dlls)之间使用STL(TR1)shared_ptr是否安全

C++“无法将参数声明为抽象类型

c++ - C++ 宏的可选参数

C++ 代码在 VS2010 中工作但在 2013 中不工作

c++ - const 对象的代码大小

c++ - 循环遍历结果集

c++ - 尝试使用 CPP 在一个 Qt 窗口中显示多个 png 文件