zoukankan      html  css  js  c++  java
  • 《C++ Primer》学习笔记:3.3.3其他vector操作

    《C++ Primer》(第五版)中计算vector对象中的索引这一小节中,举例要求计算各个分数段各有多少个成绩。

    代码如下:

    #include <iostream>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    int main(){
        vector<unsigned> scores(11, 0);
        unsigned grade;
        while (cin >> grade){
            if (grade <= 100)
                ++scores[grade/10];
        }
        return 0;
    }

    当需要输出时,自己试着敲入:

    cout << scores << endl;

    发现程序报错:

    error: invalid operands to binary expression ('ostream'
          (aka 'basic_ostream<char>') and 'vector<unsigned int>')

    发现是类型问题,所以重新定义一下scores类型,使用范围for语句:

    for (auto i : scores)
        cout << i << " ";
    cout << endl;

    改为:

    #include <iostream>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    int main(){
        vector<unsigned> scores(11, 0);
        unsigned grade;
        while (cin >> grade){
            if (grade <= 100)
                ++scores[grade/10];
        }
        for(auto i : scores)
            cout << i << " ";
        cout << endl;
        return 0;
    }

    这样就能把各个分数段各有多少个成绩序列打印出来了。

  • 相关阅读:
    codechef FNCS
    bzoj2653 middle
    CF698F Coprime Permutation
    CF538H Summer Dichotomy
    CF930E Coins Exhibition
    CF468D Tree
    CF528E Triangles3000
    BZOJ 4066: 简单题
    BZOJ 4300: 绝世好题
    BZOJ 4520: [Cqoi2016]K远点对
  • 原文地址:https://www.cnblogs.com/weixuqin/p/6484918.html
Copyright © 2011-2022 走看看