You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++排列输出格式问题:仅在前两个元素后添加逗号

问题:字符串列表全排列输出的格式修正

需求实现:

  • 读取单字名称存入vector<string>,输入-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;
}

问题分析

  1. 提前添加逗号:main函数中直接给每个名称拼接","存入容器,导致后续输出时每个元素自带逗号,无法灵活控制格式。
  2. 输出逻辑混乱:递归终止时的输出代码重复且无效,既循环输出排列列表加空格,又循环空的原始列表,完全不符合格式要求。

修正后的代码

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

using namespace std;

void AllPermutations(vector<string>& permList, vector<string>& nameList) {
    if (nameList.empty()) {
        // 输出当前排列,仅在前两个元素后添加逗号
        for (size_t i = 0; i < permList.size(); ++i) {
            cout << permList[i];
            // 前两个元素后加逗号,后续元素之间用空格分隔(最后一个元素不加符号)
            if (i == 0 || i == 1) {
                cout << ", ";
            } else if (i != permList.size() - 1) {
                cout << " ";
            }
        }
        cout << endl;
        return;
    }

    for (size_t i = 0; i < nameList.size(); ++i) {
        vector<string> 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;
}

关键修改说明

  1. 移除提前拼接的逗号:main函数中不再给名称添加",",保持原始字符串存储,格式控制交给输出逻辑处理。
  2. 重构输出逻辑:递归终止时,遍历当前排列列表:
    • 第1、2个元素(索引0、1)输出后添加", "
    • 第3个及以后的元素,除最后一个外,输出后添加空格
    • 最后一个元素直接输出,避免末尾多余符号
  3. 清理无效代码:删除原递归终止部分中循环空列表的无效代码,简化逻辑。

内容的提问来源于stack exchange,提问作者sy10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:54:53