通过ifstream输入的字符串在存储到数组之前按字母顺序排序,寻求建议
C++ Seeking advice on alphabetically sorting strings inputted via ifstream BEFORE storing in array
我花了一上午的时间研究如何从.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;
}
相关文章:
- vim 标签导航,使用 VIM 或 CTAG 更改排序顺序
- 集成多态可扩展排序顺序
- 如何修改函数以按C++的排序顺序插入每个项目
- 按排序顺序将节点插入链表
- 在C std :: Priority_queue中反向字母排序顺序的简单方法
- std::map 的排序顺序取决于输入值
- 一种按排序顺序保持元素的数据结构,支持快速插入和计算连续元素之间的最大差异
- 将随机数插入排序顺序为C++的数组中
- C++链表-按排序顺序打印
- STL 按排序顺序存储数字
- 基于最大公分的排序顺序
- 用于插入大部分排序数据的数据结构,这些数据将保持排序顺序
- 将范围有限的浮点数转换为无符号的整数,以保持排序顺序和精度
- 在排序时更改排序顺序是否是未定义的行为
- 排序顺序问题
- QSqlQuery 忽略 SQLite DB 的排序顺序
- 按排序顺序迭代 std::vector
- 使用不同的比较保持相同的排序顺序
- 按排序顺序更新文件
- 如何按排序顺序生成数组的所有排列