C++如何在每行的前两个项目上添加逗号,而不是排列中的第三个项目?

c9qzyr3d  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(96)

编写一个程序,列出人们可以排队拍照的所有方式(字符串列表的所有排列)。该程序将一个单词名称的列表读入向量nameList(直到-1),并使用递归函数创建和输出这些名称的所有可能的排序,这些名称由逗号分隔,每行一个排序。

我在输出中除了逗号之外,所有内容都是正确的,我可以在每个单词后添加逗号,但我只需要在每行的前两个单词后添加逗号。我需要在这第一张图片中看到的输出。

下面是我的代码:

#include <vector>
#include <string>
#include <iostream>

using namespace std;

void AllPermutations (vector<string> &permList, vector<string> &nameList) {
    vector<string> tmpVec; 

    if (nameList.size() == 0) {
    for (size_t i = 0; i < permList.size(); i++){
            cout << permList.at(i) << " ";
        }
        cout << endl;
        bool first = true;
        for (auto const& e: nameList) {
           if (first) { first = false; } 
           else { cout << ", "; }
           cout << e;
        
    }
}
    else {
        for (size_t i = 0; i < nameList.size(); i++){
            tmpVec = nameList;

            permList.push_back(tmpVec[i]);
            tmpVec.erase(tmpVec.begin() + i);

            AllPermutations(permList, tmpVec);

            permList.pop_back();
        }
    }
}
int main() {
   vector<string> nameList; 
   vector<string> permList; 

   string name;
   cin >> name; 
    
   while (name != "-1") {
       nameList.push_back(name+","); 
       cin >> name;
    } 

    AllPermutations(permList, nameList); 

   return 0;
}
pbpqsu0x

pbpqsu0x1#

我是说,虽然不好看但是。..

#include <vector>
#include <string>
#include <iostream>

using namespace std;

void AllPermutations (vector<string> &permList, vector<string> &nameList) {
    vector<string> tmpVec;

    if (nameList.size() == 0) {
    for (size_t i = 0; i < permList.size(); i++){
            if(i+1 == permList.size())
                cout << permList.at(i) << " ";
            else
                cout << permList.at(i) << ", ";
        }
        cout << endl;
        bool first = true;
        for (auto const& e: nameList) {
           if (first) { first = false; }
           else { cout << ", "; }
           cout << e;

    }
}
    else {
        for (size_t i = 0; i < nameList.size(); i++){
            tmpVec = nameList;

            permList.push_back(tmpVec[i]);
            tmpVec.erase(tmpVec.begin() + i);

            AllPermutations(permList, tmpVec);

            permList.pop_back();
        }
    }
}

int main(int argc, char *argv[])
{
    
    vector<string> nameList;
    vector<string> permList;

    string name;
    cin >> name;

    while (name != "-1") {
       nameList.push_back(name);
       cin >> name;
    }

    AllPermutations(permList, nameList);

    return 1;
}

输出:

Julia
Lucas
Mia
-1
Julia, Lucas, Mia 
Julia, Mia, Lucas 
Lucas, Julia, Mia 
Lucas, Mia, Julia 
Mia, Julia, Lucas 
Mia, Lucas, Julia

相关问题