循环通过c ++中的数组 [英] loop through an array in c++

查看:129
本文介绍了循环通过c ++中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想循环通过一个数组,我有一个最大值为1000.我正在填充数组从文本文件的值。我试图循环通过该数组,但在我的for循环,我不知道数组的长度,所以我不知道什么放在for循环语句的第二部分。例如:我有一个名为 int scores [1000]; 的数组,我试图迭代这个数组并将分数放在成绩类别中。所以A = 90-100,B = 80-89,C = 70-79,D = 60-69,F = 0-59。

I want to loop through an array that I have that has a max value of 1000. I am filling the array with values from a text file. I am trying to loop through that array but in my for loop, I do not know the length of the array, so I do not know what to put in the second part of the for loop statement. For example: I have an array called: int scores[1000]; and I am trying to iterate through this array and putting scores in a grade category. So A = 90-100, B = 80-89, C = 70-79, D = 60-69, F = 0-59.

我的for循环如下:

for(int i = 0; i < ...; i++){

if(scores[i] > = 90 || scores[i] <= 100){

//Do stuff...

}

我想我也很困惑如何获得每个类别的总计数结束了。但在大多数情况下,它如何迭代通过这个数组。我知道sizeof(scores [])不会工作,因为这将给我的int大小,而不是数组本身的长度。感谢,虽然提前!

I guess I am also confused as to how to get the total counts of each category at the end too. But for the most part its how to iterate through this array. I know sizeof(scores[]) wont work because that will give me the int size and not the length of the array itself. Thanks though in advance!

推荐答案

如果使用 std :: vector =http://www.cplusplus.com/reference/vector/vector/ =nofollow>链接),您可以添加元素并使向量动态更改大小。该大小可以使用 size()方法轻松查询。如果你使用这样的数组,你必须跟踪自己的元素数量。

If you use an std::vector (link) instead, you can add elements and have the vector dynamically change size. That size can be queried easily using the size() method. If you use arrays like this, you have to keep track of the number of elements in it yourself.

如果你有一个向量填充元素,你的循环可能看起来像这样:

If you have a vector filles with elements your loop could look like this:

std::vector<int> scores;
// fill vector

for (unsigned int i=0; i<scores.size(); i++) {
  // use value
}

如果你必须使用数组并且实际上有一个 scoreCount

If you have to use arrays and actually have a scoreCount variable with the number of real values put in there, simply use that in your loop:

for (int i=0; i<scoreCount; i++) {
  // use value
}

第三个选项,如我在评论中提到的,将初始化整个数组与你从来不使用的值(通常-1),然后使用它作为填充VS空数组位置的标记,如:

A third option, as I mentioned in the comments, would be initializing the whole array with a value that you're never using (typically -1) and then use that as a marker for filled vs empty array positions like so:

for (int i=0; i<1000; i++) {
    scores[i] = -1;
}

// add real values to scores 

int i=0;
while (scores[i] != -1 && i < 1000) {
  // use value
  i++;
}

这篇关于循环通过c ++中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆