加速C++(第3.2.1节:vector <double>作业)

Nei*_*ham 1 c++ vector

在第3.2.1-在"加速C++"一书的第42页上的向量中存储数据集合中,我在遵循它告诉我键入的内容后发现了我的代码中的错误.

// 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);
Run Code Online (Sandbox Code Playgroud)

我理解向量的概念,但我根本不明白为什么我的代码给了我一个特别指向的错误消息

vector<double> homework;
Run Code Online (Sandbox Code Playgroud)

宣言.C++ 11和C++ 14不再支持向量的这个声明吗?

这是我的确切代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 7

std::vector位于标题中<vector>.为了使用它,标头需要包含在您的代码中.要做到这一点你需要#include <vector>.那么你还需要有一个using std::vector;或使用std::vector.