作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要编写书名排序的 C++ 代码:
我能够做到第一个,但我在显示书籍的字母顺序时遇到了困难。
这是我的代码:
#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/
Book_title Table +---------------+-------------------+ | isbn | title | +------
如何删除 PHP 中的所有 HTML 标记,除了 <>人物? //There's other HTML tags, like h1, div, etc. echo strip_tags(' a hot
我是一名优秀的程序员,十分优秀!