c++ - 对字符串指针数组进行排序

标签 c++ arrays string sorting

我的 sortArray 函数中的交换函数似乎无法正常工作。错误是: No viable overloaded operator[] for type 'string *' (aka 'basic_string<char, char_traits<char>, allocator<char> > *') .

我设法找到了输出中排在第一位的项目,但现在我只需要一点帮助,让其余的用户输入按预期显示。 回顾一下,该程序需要从用户那里读入那么多单字名称(每个 Pokemon 一个),并将这些名称存储在一个数组中。用户输入完名字后,程序应显示用户输入的所有口袋妖怪的列表,但按字母顺序排列。我得到的最远输出是:

Welcome! How many Pokemon do you own?

4

Ok, enter the names!

Pikachu

Snorlax

Ekans

Squirtle

输出:

Thanks, here are the pokemon you entered: Ekans Ekans Ekans Ekans Program ended with exit code: 0

这是我的代码:

#include <iostream>
#include "playground.h"
using namespace std;

string findFirst(string *x, int start, int end)
{
    string first = x[0];
    for(int i=start; i <= end; i++)
    {
        if(x[i] < first)
        {
            first = x[i];
        }
    }
    return first;
}

void sortArray(string *items, int start, int end)
{
    for(int i=start; i<=end; i++)
    {
        string min = findFirst(items,i, end);
        swap(items[i], items[min]);
    }
}


int main()
{
    cout<<"Welcome! How many Pokemon do you own?"<<endl;
    int num = 0;
    cin >> num;

    cout<< "Ok, enter the names!"<<endl;
    string *names = new string[num];
    for(int i=0; i<num; i++)
    {
        cin>>names[i];
    }
    cout<<"Thanks, here are the pokemon you entered: ";
    for(int i=0; i<num; i++)
    {
        cout << sortArray(names, 0, num) << " ";
    }        

    return 0;
}

最佳答案

C++ 就是不重新发明轮子。它专为编写库和通用代码而设计,例如 STL(标准模板库)。

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

using namespace std;  // Kids, do not try this at home

int main() {
    cout << "Welcome! How many Pokemon do you own?" << endl;
    int num = 0;
    cin >> num;
    cout << "Ok, enter the names!" << endl;
    std::vector<std::string> names(num);
    for (auto &name: names) {
        cin >> name;
    }

    std::sort(names.begin(), names.end());

    cout << "Thanks, here are the pokemon you entered: ";
    for (auto name: names) {
        cout << name << " ";
    }
    cout << endl;
    return 0;
}

关于c++ - 对字符串指针数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49080060/

相关文章:

c++ - CUDA 内核调用阻塞?

c++ - C++游戏引擎中的组合、组件和实体

c++ - 安全阵列删除

c - 为什么 scanf 不需要字符串的符号并且在 printf 中也能正常工作(在 C 中)?

c++ - 琐碎的分配器感知容器?

java - 在函数调用中,入口日志的数量远少于导出日志的数量。这是为什么?

node.js - 将字符串转换为数字 node.js

ruby - 获取ruby中所有字符的索引

Python根据条件查找数组中的索引

php - 多选字段仅提交最后选择的选项