我有一个列表,我需要按字母顺序排序,但是在这种情况下,由于该列表最初是按时间顺序列出的,因此我还需要保持其原始位置。我已经按字母顺序对列表进行了排序,但我不知道如何添加按时间顺序排列的位置。
有任何想法吗?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("prez.dat");
ofstream fout("sorted.dat");
void main()
{
//fin.open("prez.dat");
//fout.open("sorted.dat");
vector<string> names;
if(!fin.is_open())
{
cout << "Unable to open file..." << endl;
}
string word;
while(getline(fin, word))
names.push_back(word);
sort(names.begin(), names.end());
for (size_t i=0; i <names.size(); i++)
cout << names[i] << '\n';
system("pause");
}//End of void main()
编辑:我正在寻找:
该文件如下所示:
苹果
橙子
香蕉
我需要的是:
苹果1
香蕉3
橙色2
最佳答案
一种解决方法是将输入字符串和原始序数位置都保留在一个对象中。然后仅根据对象的字符串部分进行排序,然后为每个对象同时发出字符串和原始顺序位置。
例如,对于您的班级,您可以这样:
class MyData {
private:
std::string s; // the string read from the file
unsigned ord; // original position of the string
public:
// standard constructor
MyData(std::string str, unsigned order) : s(str), ord(order) {}
// this allows you to use "std::cout << md;"
friend std::ostream& operator<<(std::ostream& out, const MyData &m) {
return out << m.s << ' ' << m.ord;
}
static bool cmp(const MyData &a, const MyData &b) {
return a.s < b.s;
}
};
然后,您所需要做的就是创建并推送对象,并定义一个用于
std::sort
的比较操作。有关详细信息和如何执行此部分的示例,请参见this reference。这是一种方法:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
// MyData code goes here
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cout << "Usage: sortfile filename\n";
return 0;
}
std::vector<MyData> vec;
std::string line;
int i=1;
for(std::ifstream in(argv[1]); std::getline(in, line); ++i)
vec.push_back(MyData(line, i));
std::sort(vec.begin(), vec.end(), MyData::cmp);
std::cout << "vec contains:\n";
for (auto md : vec)
std::cout << md << '\n';
}
当编译时(作为C ++ 11),从这个我称为
fruit.txt
的输入文件中:Apple
Orange
Banana
使用文件
./sorted fruit.txt
可得到以下结果:vec contains:
Apple 1
Banana 3
Orange 2