#include <vector>
#include <iostream>
#include <fstream>
#include<sstream>
#include <algorithm>
using namespace std;
using PAIR = pair<string, size_t>;
bool ReadFile(vector<PAIR>& words) {
ifstream infile;
infile.open("text.txt", ios::in);
if (!infile.is_open())
{
cout << "读取文件失败" << endl;
return -1;
}
string line, word;
size_t word_line = 1;
while (getline(infile, line))//逐行读
{
istringstream istrm(line);//创建字符串流
while (istrm >> word)//逐单词读
{
transform(word.begin(), word.end(), word.begin(), ::tolower);
words.push_back({ word, word_line });
}
word_line += 1;
}
infile.close();
return 0;
}
bool Compare(const string& a, const string& b, unsigned int n = 0) {
if (a.length() == n && b.length() == n) {
return false;
}
else if (a.length() == n) {
return true;
}
else if (b.length() == n) {
return false;
}
if (a[n] > b[n]) {
return false;
}
else if (a[n] == b[n]) {
Compare(a, b, ++n);
}
else {
return true;
}
}
bool MySort(const PAIR& first, const PAIR& end) {
return Compare(first.first, end.first);
}
void show(const vector<PAIR>& words) {
size_t num = 1;
for (size_t i = 0; i < words.size(); ++i) {
if (i != words.size() - 1 && words[i].first == words[i + 1].first) {
++num;
continue;
}
cout << words[i].first << " " << num << " ";
while (num--) {
cout << words[i - num].second << " ";
}
cout << endl;
num = 1;
}
}
int main() {
vector<PAIR> words;
if (ReadFile(words) == -1) {
return -1;
}
sort(words.begin(), words.end(), MySort);
show(words);
return 0;
}
交叉引用生成器
最新推荐文章于 2025-03-10 10:21:52 发布