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

时间:2015-08-25 17:46:41

标签: c++ vector

在“加速C ++”一书的第42页 3.2.1 - 在向量中存储数据集一节中,我在遵循它告诉我键入的内容时遇到了错误

// 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<double> homework;

声明。 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;
}

1 个答案:

答案 0 :(得分:7)

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