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

C++中如何将list转为动态数组,用于实现冒泡排序?

将std::list转换为动态数组并实现冒泡排序的方案

你可以通过动态分配数组(new关键字)或者使用std::vector(C++标准库的动态数组容器,更安全省心)来完成list到数组的转换,下面分两种方法说明:

方法一:手动分配动态数组

这种方法需要自己管理内存,步骤清晰:

  • 用new int[b]分配对应大小的数组
  • 遍历list把元素复制到数组
  • 完成排序后用delete[]释放内存,避免内存泄漏

修改后的完整代码:

#include "Log.h"
#include <array>
#include <list>
#include <ctime>
#include <memory>
#include <iostream> // 必须包含才能使用cout/cin

using namespace std;
void Initlog();
void Log(const char* message);

int main()
{
    Initlog();
    int a;
    int b;
    list<int> list1;

    cout << "请输入要生成的随机数个数: ";
    cin >> b;

    cout << "请输入随机数的最大值: ";
    cin >> a;
    srand(time(0)); // 初始化随机数种子
    for (int i = 0; i < b; i++)
    {
        int x = rand() % a;
        cout << x << "\n";
        list1.push_back(x);
    }

    cout << "插入所有元素后的列表: ";
    for (list<int>::iterator i = list1.begin(); i != list1.end(); i++)
        cout << *i << " ";
    cout << endl;

    // 把list转换为动态数组
    int* arr = new int[b];
    int idx = 0;
    for (int num : list1) {
        arr[idx++] = num;
    }

    // 冒泡排序实现
    for (int i = 0; i < b - 1; i++) {
        for (int j = 0; j < b - i - 1; j++) {
            if (arr[j] > arr[j+1]) {
                // 交换两个元素
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }

    // 输出排序结果
    cout << "排序后的数组: ";
    for (int i = 0; i < b; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // 释放动态数组内存,必须做!
    delete[] arr;

    std::cin.get();
    std::cin.get(); // 防止程序运行后直接退出
}

方法二:使用std::vector(更推荐)

std::vector是C++专门的动态数组容器,自动处理内存分配和释放,不用手动调用new/delete,新手用起来更不容易出错:

替换数组转换和排序的代码段即可:

// ... 前面生成list的代码不变 ...

// 把list元素复制到vector
vector<int> vec;
vec.assign(list1.begin(), list1.end());

// 冒泡排序vector
int n = vec.size();
for (int i = 0; i < n - 1; i++) {
    for (int j = 0; j < n - i - 1; j++) {
        if (vec[j] > vec[j+1]) {
            swap(vec[j], vec[j+1]); // 用std::swap简化交换操作
        }
    }
}

// 输出排序后的结果
cout << "排序后的数组: ";
for (int num : vec) {
    cout << num << " ";
}
cout << endl;

std::cin.get();
std::cin.get();

两种方法都能满足你的需求,vector因为不需要手动管理内存,安全性更高,更适合新手使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:06:19