C ++:“vector< int> :: size_type variable” - 以这种方式宣告的意义是什么? [英] C++: "vector<int>::size_type variable" - what is the point of declaring in this way?

查看:125
本文介绍了C ++:“vector< int> :: size_type variable” - 以这种方式宣告的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是一个非常基本的问题,但我不能只是计算出来。

I think this is a very basic question but I couldn't just figure it out.

我习惯于在C ++中使用数组,但我现在开始学习向量。
我在做一个测试代码,我遇到了一个问题。

I was used to using arrays in C++ but I'm now starting to learn vectors. I was making a test code, and I came across a question.

首先,这是我做的代码:

First of all, here's the code I made:

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main(){
  vector<double> score(10);

  for(vector<double>::size_type i=0;i<20;i++) {
    cout<<"Enter marks for student #"<<i+1<<":"<<flush;
    cin>>score[i];
  }

  double total = accumulate(score.begin(), score.end(),0);

  cout<<"Total score:"<<total<<endl<<"Average score:"<<total/score.size()<<flush;

  return 0;
}



<我将 i 声明为 向量< double> :: size_type 类型(因为我被告知这样做)。
我测试的代码与上述类型替换为 int ,它的工作完全正常。
为什么 向量< double> :: size_type int

In the for sentence in line #9, I am declaring i as a vector<double>::size_type type (because I was told to do so). I tested the code with the type said above replaced with an int, and it worked perfectly fine. Why is vector<double>::size_type preferred compared to int?

推荐答案

size_type 对于最大支持的向量大小, vector :: max_size()足够大。 int 不是:在许多通用平台上, int 有32位,而 max_size

size_type is guaranteed to be large enough for the largest supported vector size, vector::max_size(). int is not: on many common platforms, int has 32 bits, while max_size() is considerably larger than 231.

这篇关于C ++:“vector&lt; int&gt; :: size_type variable” - 以这种方式宣告的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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