简体   繁体   中英

Printing array of vectors on c++

I am trying to print an array of vectors in c++. The program works when I leave out "const" in the parameter list and the "for each" loop. When I insert the const type qualifiers, it gives me an error.

Here is my main function with the function call to print list:

int main() {
    std::cout << "Hello World\n";

    std::vector<Employee> employeeList {};

    // Entering employee data 
    buildList(employeeList);


    //print the list of employees.
    printList(employeeList);

    //pause code
    int pause;
    std::cin >> pause;
    return 0;
}

Here is the print list definition:

void printList(std::vector<Employee> &list) {
    //use a for each loop to print each employee
    int index = 0;
    for (auto &element : list) {
        std::cout << "\n";
        std::cout << "Employee: " <<(index+1)<<     std::endl;
        element.printEmployee();
        index++;
    }

}

Again, when I place const in the parameter list and the for each loop, it gives me an error. Why?

Here is an image of the error:

screen capture of the code giving the error

The declaration of Employee::printEmployee is incorrect. It must be void Employee::printEmployee() const for it to be used in a const context.

For future reference, what you are calling a for each loop is called a "range-based for loop" or "range-based for". Calling it a for each loop can be confused with the actual algorithm std::for_each and should be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM