0

Alrighty, so what I am trying to do is print off a vector of 20 last names onto the command line. (This is not all I'm trying to do in this particular case, but for clarification I am trying to print out 20 students information on the command line, the information being their ID number, last name, and age. I'll post the vector first and then the function that is calling for all the information to be gathered below (age is missing because I haven't got to it yet) But my question is, am I using this vector of strings correctly? When I compile I am told that

"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 >'|"

The type of answer I'm hoping to find is why I am getting this error, how I can fix it, and how I can avoid having this problem next time. Thanks everyone!

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;
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480

1 Answers1

1

The error this code gives me when compiled simply using g++ code.cpp is:

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

This is because you are using std::initializer_list, which is available from C++11 onwards. You should compile your code using: g++ code.cpp -std=c++11 (or using a compiler that supports C++11 by default).

You also have a small mistake: use std::vector::size() method instead of length().

Lastly, proper way to iterate through vector would be to use iterator or a range-based for loop.

syntagma
  • 23,346
  • 16
  • 78
  • 134