将两个矢量并排打印到屏幕上

Printing two vectors to screen in columns next to each other?

本文关键字:打印 屏幕 两个      更新时间:2023-10-16

因此,我的程序使用while循环来填充两个单独的向量,方法是询问项目的名称(向量一),然后询问项目的价格(向量二)。

    double ItemCost;
    vector<double> Cost;
    string ItemName;
    vector<string> Item;
        while (ItemName != "done")
        {
            cout << "Item name: "; cin >> ItemName;
            Item.push_back(ItemName);// gets item name from use and stores in the vector "Item"
            if (ItemName != "done") 
            {
                cout << "Item cost: $"; cin >> ItemCost;
                Cost.push_back(ItemCost);// gets cost of item and stores it in the vector "cost"
            }
            else
            {
                continue;
            }
    }
system("CLS");

所以在清除屏幕之后,我希望程序输出一个屏幕,显示项目名称,然后在右边显示成本。然后在下一行对第二项输入执行相同的操作。基本上像这样显示:

cout << Item[0]; cout << "         $" << Cost[0];
cout << Item[1]; cout << "         $" << Cost[1] << endl;
cout << Item[2]; cout << "         $" << Cost[2] << endl;

但是,无论输入多少项,我都希望它这样做,而且按照我上面的方式做显然是一个坏主意,如果他们输入的量小于我在代码中的量,因为程序会试图访问向量占用的内存等之外。这只是举一个我想要的格式的例子。

如果向量大小相同,可以使用简单的for循环来迭代内容:

for (int i = 0; i < Item.size(); ++i) {
    cout << Item[i] << " $" << Cost[i] << endl;
}

在运行此代码之前,您可能需要使用调试断言检查这两个向量的大小是否相同:

assert(Item.size() == Cost.size();

或者,您可以使用类似std::min的东西来只循环两个向量中最小的一个,以防它们大小不同。

我建议使用std::pairstd::vector将价格和项目存储在一起,这只是因为它可以跟踪哪个价格与哪个项目相关。这消除了检查两个矢量大小是否相同的需要,并最大限度地减少了发生错误的可能性。然后,使用基于范围的for循环来遍历每一对并打印它们就很简单了。我在下面展示了一个带有一些改进的示例。与简单结构相比,使用std::pair有很多优点,其中一个优点是包含了在类似std::sort()的结构中使用的必要布尔函数,如果使用该函数,基本上会按字母顺序对项目列表进行排序。如果您想对代码进行未来验证,这是非常有用的。

double ItemCost;
string ItemName;
vector<std::pair<string, double> > Item;
    while (ItemName != "done")
    {
        cout << "Item name: "; 
        // Using std::getline() as it terminates the string at a newline.
        std::getline(std::cin, ItemName);
        if (ItemName != "done") 
        {
            cout << "Item cost: $"; cin >> ItemCost;
            Item.push_back(std::make_pair (ItemName,ItemCost));
        }
        else
        {
            continue;
        }
    }
system("CLS");
// Printing here using c++11 range based for loop, I use this extensively
// as it greatly simplifies the code.
for (auto const &i : Item)
{ 
    std::cout << i.first << "tt$" <<  i.second;
                         //  ^^ Using double tab for better alignment
                         //     instead of spaces.
}
Vector知道它有多大,所以有很多简单的解决方案,最简单的是
for (size_t index = 0; index < Item.size() && index < Cost.size(); index++)
{
    cout << Item[index]; cout << "         $" << Cost[index] << endl;
}

但一个更好的想法是有一个vector来存储类似的东西

struct ItemCost
{
    string name;
    double cost; // but it's generally safer to store money by pennies in integers
                 // You can't always count on floating point numbers in comparisons
}

这样一来,项目和成本就永远不会失去同步。

阅读此处了解更多关于浮点在货币等精确事物中失败的原因:比较浮点值有多危险?