我有一个函数打印出一个包含类项的2D矢量。这是向量:
std::vector<vector<item>> notepad;
在我的课程项目中,每个项目都有私人成员:
std::string name;
double price;
int quantity;
这些是相关的成员函数:
double item::getPrice()
{
return price;
}
void item::setQuantity(int itemQuantity)
{
quantity = itemQuantity;
}
int item::getQuantity()
{
return quantity;
}
这是打印列表的功能:
void list::printLists(bool printTotalPrice)
{
if (isEmpty() == true)
{
std::cout << "You have not added any lists yet." << std::endl;
}
else
{
std::vector<std::vector<item>>::iterator row;
std::vector<item>::iterator col;
for (row = notepad.begin(); row != notepad.end(); ++row)
{
double total = 0;
std::cout << "------------------------------------------" << std::endl;
for (col = row->begin(); col != row->end(); ++col)
{
if (col == row->begin()) //first item of user-created lists contain list name only
{
std::cout << "List Name: " << col->getName() << std::endl;
}
else
{
std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
std::cout << "Item: " << col->getName() << std::endl;
std::cout << "Price: " << col->getPrice() << std::endl;
std::cout << "Quantity: " << col->getQuantity() << std::endl;
std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
}
if (printTotalPrice == true)
{
total += (col->getPrice()) * (col->getQuantity());
}
}
这是编译和运行时的结果:
------------------------------------------
List Name: Apples
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Item: 0x609ca8Eggs
Price: 0x609ca80.1
Quantity: 0x609ca8-12
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Item: 0x609ca8Bread
Price: 0x609ca81
Quantity: 0x609ca8-3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Item: 0x609ca8Pizza
Price: 0x609ca810
Quantity: 0x609ca8-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Item: 0x609ca8Peanut Butter
Price: 0x609ca83.25
Quantity: 0x609ca8-2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Item: 0x609ca8Bananas
Price: 0x609ca80.79
Quantity: 0x609ca8-6
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Item: 0x609ca8Salmon
Price: 0x609ca813.2
Quantity: 0x609ca8-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Item: 0x609ca8Rib Eye
Price: 0x609ca820.2
Quantity: 0x609ca8-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Item: 0x609ca8Spinach
Price: 0x609ca81.25
Quantity: 0x609ca8-3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Item: 0x609ca8Tomatoes
Price: 0x609ca80.59
Quantity: 0x609ca8-5
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
------------------------------------------
------------------------------------------
List Name: MyList
知道如何修复格式化吗?