通过ifstream输入的字符串在存储到数组之前按字母顺序排序,寻求建议

C++ Seeking advice on alphabetically sorting strings inputted via ifstream BEFORE storing in array

本文关键字:排序 顺序 字符串 输入 ifstream 存储 数组 通过      更新时间:2023-10-16

我花了一上午的时间研究如何从.txt文件中读取单词并将它们存储在动态数组中。然而,我的目标是在输入单词时按字母顺序排序。为了找到答案,我做了尽可能多的研究,但还是找不到解决办法。

我知道动态数组当前取预定值,但现在这并不重要。

我只是在寻找方向,什么都可以。这是我目前所看到的:

ARRAYSTORAGE.CPP

#include <fstream>
#include <iostream>
#include <ostream>
#include <string>
#include "ArrayStorage.h"
using namespace std;

void ArrayStorage::read(ifstream &fin1)
{
    int index = 0;
    string firstTwo;
    const int arrayLength = 4160;
    string* arrayOfWords;
    arrayOfWords = new string[arrayLength];
    if(fin1.is_open())
        {
            fin1 >> firstTwo;
            fin1 >> firstTwo;
            while(!fin1.eof())
            {
                fin1 >> arrayOfWords[index];
                cout << arrayOfWords[index];
                cout << "n";
                index++;
            }
            delete [] arrayOfWords;
            fin1.close();
        }
}

HEADER.CPP

//认为无关紧要的

MAIN.CPP

//认为无关紧要的

谢谢!

您可以将它们放在set/multiset中(如果您可以有重复项,则使用前者),每次插入后都会对其进行排序。

如果您可以放弃对元素进行动态排序的要求,我建议使用以下方法。除此之外,我还更改了返回类型,并决定不关闭fstream

#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include "ArrayStorage.h"
std::vector<std::string> ArrayStorage::read(std::ifstream &fin)
{
    std::vector<std::string> words;
    std::string word;
    while (fin >> word)
    {
        words.push_back(word);
    }
    if (words.size() >= 2)
    words.erase(words.begin(), words.begin() + 2);
    std::sort(words.begin(), words.end());
    return words;
}