0

当它返回输出时,我一直试图在这个列表中添加数量。它本质上是一个由用户输入的列表,以数量开头,后跟一个单词。然后它应该按字母顺序输出相同的列表。我目前已将其按字母顺序排列,但用户在同一行输入的数字在按字母顺序返回时会在与单词不同的行中返回。我知道我被提示使用并行数组,但不知道如何将它们合并到其中。没有人能够回复我,但我知道这是可行的。谢谢大家!!

#include <iostream>
#include <string>
#include <iomanip>
#include "functions.h"
#include <algorithm>
#include <set>
using namespace std;


void print(const string& item)
{
    cout << item << endl;
}


int main(void)
{
    const int MAX_LENGTH = 256;
    string items [MAX_LENGTH];
    int quantities [ MAX_LENGTH];
    string itemChoice;
    string qtyChoice;
    int numItems= 0;

    int randomArray[MAX_SIZE];  

    {
        set<string> sortedItems;

        cout <<  " (type \"exit\" twice to exit, now press enter twice to begin listing your shopping list.): ";

        getline (cin, qtyChoice);
        getline(cin, itemChoice);

        for (int i = 1; ; i++)
        {
            string itemChoice;
            string wholeOrder;
            cout << i << ". ";
            cin >> itemChoice;
            cin >> qtyChoice; // this is how I got it to intake #'s
            //getline (cin, qtyChoice);// putting these here actually allow both items to be on one line!! but it leaves awkward spaces.
            //getline(cin, itemChoice);
            //getline (cin, qtyChoice);

            if (itemChoice == "exit")
            {
                break;
            }

            sortedItems.insert(qtyChoice);
            sortedItems.insert (itemChoice);
            //sortedItems.insert(itemChoice);   
        }


        for_each(sortedItems.begin(), sortedItems.end(), &print);


        return 0;
    }

这是我的代码,这是作为输出发生的

(type "exit"to exit, now press enter twice to begin listing your list.):

1. 3828 eijsd
2. 38238 shd
3. 382 hsdid
4. exit
382
38238
3828
eijsd
hsdid
shd
4

1 回答 1

0

你不区分集合中的数量和单词,因此它们被视为同一种事物,它们之间没有任何联系。要保留连接,您需要更复杂的数据结构。

使用并行数组是一种可能,但开销是一种痛苦。比一对数组更简单的方法是一对数组——更好的是一对数组set,因为您已经知道集合提供了简单的排序。(Amap也可以。)

set< pair<string,string> > sortedItems;

将单词和数量都存储在对中保留了它们之间的关系。我将留给您填写其余的详细信息。

于 2019-01-18T12:47:39.857 回答