简体   繁体   English

C ++中用户定义数组的问题

[英]Issue with user-defined array in C++

I am trying to create an array using cin to define the size. 我正在尝试使用cin创建一个数组来定义大小。 While that seems to be working (based on what I currently have), none of the other stuff I want to do seems to be working. 尽管这似乎行得通(根据我目前的情况),但我想做的其他事情似乎都没有。

For instance, I want to use a for loop to find the smallest int in the array since I will then need to compare it with all the other ints in the array, but no matter where I have the statement to return the smallest int, it does not do it. 例如,我想使用一个for循环在数组中查找最小的int,因为随后我需要将其与数组中的所有其他int进行比较,但是无论我在哪里有返回最小int的语句,它不这样做。

What am I doing wrong? 我究竟做错了什么?

#include <iostream>

using namespace std;

int main(){


  int userSize;
  cout << "Please define size of array: ";
  cin >> userSize;

  int *duckArray = new int[userSize];

  for (int i = 0; i < userSize; i++) {
    cout << "Please enter a number into the array: ";
    cin >> duckArray[i];
  }

  int smallest = duckArray[0];

  for (int i = 0; i < userSize; i++){
    if (duckArray[i] < smallest){
        smallest = duckArray[i];
        cout << smallest << endl;
    }
  }

  //cout << smallest << endl;

  return 0;
}

Your code is working if you change this: 如果您更改此代码,则代码正常工作:

for (int i = 0; i < userSize; i++){
    if (duckArray[i] < smallest){
        smallest = duckArray[i];
    }
}

cout << smallest << endl;

This will find and print the smallest number entered. 这将查找并打印输入的最小数字。

Arrays in C++ must have their size declared to the compiler at runtime. C ++中的数组必须在运行时向编译器声明其大小。 Other people are going to explain how you can buffer memory to simulate a dynamically allocating arrays. 其他人将解释如何缓冲内存以模拟动态分配的数组。 You can also have your Array at a given size and as the user adds and removes, you can reject inputs over the current size. 您还可以使用给定大小的Array,并且当用户添加和删除时,您可以拒绝当前大小以上的输入。

I highly recommend you look into Vectors . 我强烈建议您研究Vectors Vectors are much like ArrayLists in Java. 向量非常类似于Java中的ArrayLists They are a form of higher level collections that resize themselves as you add more elements to them. 它们是高级集合的一种形式,当您向它们添加更多元素时,它们会自动调整大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM