关于c ++:我是否正确使用此向量?

Am I using this vector correctly?

本问题已经有最佳答案,请猛点这里访问。

好的,所以我要做的是把20个姓氏的矢量打印到命令行上。(这不是我在这个特殊情况下要做的全部工作,但为了澄清,我试图在命令行上打印出20个学生的信息,这些信息是他们的ID号、姓氏和年龄。我会先发布向量,然后再发布一个函数,该函数要求所有信息都收集到下面(因为我还没有达到这个年龄,所以缺少年龄),但我的问题是,我是否正确地使用了这个字符串向量?当我编译时,我被告知

"error: could not convert '{"Simmons","Jones","James","Little","Russell","Haynes","Marcotte","Kemper","Vandergore","Hume","Stephens","Jensen","Biersack","Sykes","Joseph","Dunn","Hai","Meteos","Aphromoo","Faker"}' from '' to 'std::vector >'|"

我希望找到的答案类型是为什么我会得到这个错误,我如何修复它,以及我如何避免下次出现这个问题。谢谢大家!

1
2
3
4
5
6
7
8
9
10
11
12
vector<int> studentNumber (20);
vector<string> lastName = {"Simmons","Jones","James","Little","Russell","Haynes","Marcotte","Kemper","Vandergore","Hume","Stephens","Jensen","Biersack","Sykes","Joseph","Dunn","Hai","Meteos","Aphromoo","Faker"};

void getAllStudentInfo() {
    for (vector<int>::size_type i = 0; i <= 20; i++) {
    cout <<"Student's ID number is:" << 400 + i << endl;
    }
    for (int i = 0; i < lastName.length(); i++) {
        cout << lastName[i] <<endl;
    }
    return;
}


在使用g++ code.cpp进行编译时,此代码给出的错误是:

1
so.cc:6:229: error: in C++98 ‘lastName’ must be initialized by constructor, not by ‘{...}

这是因为您使用的是STD::PrimalIZELSYLIST,它可以从C++ 11开始。您应该使用EDCOX1(1)来编译代码(或者使用默认支持C++ 11的编译器)。

还有一个小错误:使用std::vector::size()方法而不是length()

最后,通过向量迭代的正确方法是使用迭代器或基于范围的for循环。