0

我花了一上午的时间研究如何从 .t​​xt 文件中读取单词并将它们存储在动态数组中。但是,我的目标是在输入单词时按字母顺序对单词进行排序。我已经做了尽可能多的研究以找到答案,但找不到解决方案。

我知道动态数组当前正在采用预定值,但这目前并不重要。

我只是在寻找一些方向,任何事情都会很棒。这是我到目前为止所拥有的:

阵列存储.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();
        }
}

头文件

//假定无关

主程序

//假定无关

谢谢!

4

2 回答 2

0

如果您可以放弃即时对元素进行排序的要求,我建议改用以下内容。除其他外,我还更改了返回类型并决定不关闭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;
}
于 2013-05-16T16:16:50.327 回答
0

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

于 2013-05-16T17:17:30.937 回答