c++ - 加速 C++(第 3.2.1 节 : vector<double> homework)

标签 c++ vector

<分区>

在《Accelerated C++》一书第 42 页的 3.2.1 - 将数据集合存储在 vector 中 部分,我在按照代码告诉我输入的内容后遇到了代码错误.

// revised version of the excerpt
double x;
vector<double> homework;

// invariant: homework contains all the homework grades read so far
while (cin >> x)
    homework.push_back(x);

我理解 vector 的概念,但我只是不明白为什么我的代码会给我一条错误消息,特别指向

vector<double> homework;

声明。 C++11 和 C++14 是否不再支持这种 vector 声明?

这是我的确切代码:

#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <ios>
#include <string>

using std::cin;         using std::string;
using std::cout;        using std::setprecision;
using std::endl;        using std::streamsize;

int main()
{
    // ask for and read the student's name
    cout << "\n  Please enter your first name: ";
    string name;
    cin >> name;
    cout << "  Hello, " << name << "!" << endl;

    // ask for and read the midterm and final grades
    cout << "  Please enter your midterm and final exam grades: ";
    double midterm, final;
    cin >> midterm >> final;

    // ask for the homework grades
    cout << "  Enter all your homework grades, "
            "  followed by end-of-file: ";

    //the number and sum of grades read so far
    int count = 0;
    double sum = 0;

    // a variable into which to read
    double x;
    vector<double> homework;

    /*invariant:
    we have read COUNT grades so far, and
    SUM is the sum of the first COUNT grades*/
    while (cin >> x) {
        homework.pushback(x);
    }

    // write the result
    streamsize prec = cout.precision();
    cout << "  Your final grade is " << setprecision(3)
        << 0.2 * midterm + 0.4 * final + 0.4 * sum / count
        << setprecision(prec) << endl;

    return 0;
}

最佳答案

std::vector位于标题 <vector> .为了使用它,该 header 需要包含在您的代码中。为此,您需要 #include <vector> .然后你还需要有一个 using std::vector;或使用 std::vector .

关于c++ - 加速 C++(第 3.2.1 节 : vector<double> homework),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32210738/

相关文章:

c++ - 存储指向类对象的指针地址的最佳方法

c++ - 多维 vector 初始化

c++ - 用 "comma initialization"初始化静态特征矩阵

c++ - 覆盖基类无法正常工作

c++ - vector 大小在构造函数外恢复为 0

C++/带有对象指针 vector 的多个文件

java - n 维超立方体中的连接点

c++ - 在 C++ 项目中包含 dlib 库时出错

android - iostream : No such file or directory in Android NDK Environment

c++ - 使用 next_permutation 置换类 vector