CodingHowTo

Print a Neat Table from a Vector of Structs

Print a Neat Table from a Vector of Structs

Step-by-Step Guide

  1. Define a Struct
  2. Create a Vector of Structs
  3. Print the Table

Step 1: Define a Struct

First, let's define a struct that represents the data we want to display in the table. For this example, let's assume we're working with employee information.


struct Employee {
    std::string name;
    int id;
    std::string department;
};

        

Step 2: Create a Vector of Structs

Next, we'll create a vector containing multiple instances of our struct.


std::vector<Employee> employees = {
    {"Alice", 101, "Engineering"},
    {"Bob", 102, "HR"},
    {"Charlie", 103, "Marketing"}
};

        

Step 3: Print the Table

Finally, we'll iterate over the vector and print each struct in a tabular format.


std::cout << std::left << std::setw(15) << "Name" 
          << std::setw(10) << "ID" 
          << std::setw(20) << "Department" 
          << std::endl;

std::cout << std::setw(45) << std::setfill('-') << "" << std::setfill(' ') << std::endl;

for (const auto& emp : employees) {
    std::cout << std::left << std::setw(15) << emp.name 
              << std::setw(10) << emp.id 
              << std::setw(20) << emp.department 
              << std::endl;
}

        

The output will look like this:


Name             ID     Department        
----------------------------------------
Alice            101    Engineering       
Bob              102    HR                
Charlie          103    Marketing         

        

Conclusion

Printing a neat table from a vector of structs in C++ is straightforward with the use of standard library features like streams and setw. This method allows you to display data in a structured format, making it easier to read and understand.

By following these steps, you can efficiently create well-formatted tables for any data stored in vectors of structs.