gpt4 book ai didi

c++ - 冒泡排序书名

转载 作者:行者123 更新时间:2023-11-28 05:17:18 25 4
gpt4 key购买 nike

我需要编写书名排序的 C++ 代码:

  1. 显示书名。
  2. 按字母顺序显示书名。

我能够做到第一个,但我在显示书籍的字母顺序时遇到了困难。

这是我的代码:

#include"stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
#include <algorithm>
#include <cstring>
#include <map>
#include <stdlib.h>
#include <time.h>

using namespace std;

const int MAX = 5;

void BubbleSort(string books, int max);

int main(int argc, const char * argv[])
{
string books[MAX];

//inputs
std::cout << "Enter Book titles: \n";
for (int i = 0; i < MAX; i++)
{
std::cout << "Book [" << i << "]: ";
//cin >> books[i];
getline(std::cin, books[i]);

}
// print the titles stored in books[i] variable
cout << "Book Titles Entered \n\n";
for (int i = 0; i < MAX; i++)
{
std::cout << "Book No." << i << ": ";
cout << books[i] << endl;

}

// print the titles after sort
cout << "Book Titles In Sort Ascending \n\n";
for (int i = 0; i < MAX; ++i)
cout << books[i] << "\n";

}

void BubbleSort(string books, int size)
{
int result;
for (int pass = 0; pass < size - 1; ++pass)
{
for (int i = 0; i < MAX - 1 - pass; ++i)
{
result = string (books[i], books[i + 1]);
if (result > 0) {
swap(books[i], books[i + 1]);
}
}
}

system("pause");
}

最佳答案

您没有调用 BubbleSort

另一方面,除非这是家庭作业或类似的作业并且您必须实现冒泡排序,否则我建议您使用std::sort。此外,将静态数组替换为动态数组,例如 std::vector:

std::vector<std::string> books;
// <input here>: use books.push_back to insert new strings
std::sort(books.begin(), books.end());

如果您事先知道书籍的数量,您可以预先分配内存以降低插入的复杂性:books.reserve(MAX)

关于c++ - 冒泡排序书名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42365380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com