-1
對於一個類項目,我們正在製作一個運行多個線程的grep類型程序,我們需要存儲文件名和單詞匹配的行號。結果需要由行號的文件名先進行排序,然後C++按主要次序排序,然後是次要條件
所以我要
namespace ultragrep
{
class File {
public:
int lineNumber;
std::string contents;
std::string fileName;
File(int ln, std::string lc, std::string fn) : lineNumber(ln), contents(lc), fileName(fn) {};
File() {};
~File(){};
string ln_toString() {
return "[" + std::to_string(lineNumber) + "]";
}
string contents_toString() {
return " \"" + contents + "\" ";
}
};
std::ostream& operator<<(std::ostream& out, const File& f) {
return out << "[" << f.fileName << "]...";
}
//operator < so sort works
bool operator < (File& lhs, File& rhs)
{
return lhs.fileName < rhs.fileName;
}
}
,當我所有的線程在我的主要完成()我有
sort(files.begin(), files.end());
for (ultragrep::File file : files)
{
cout << file << file.ln_toString() << file.contents_toString() << endl;
}
和這看起來會返回我期待的結果,但不能保證行號也是在一組結果中排序的。
示例的結果:
[file1.txt]...[1] "clock hello"
[file4.txt]...[1] "hello hello "
[file4.txt]...[2] "hello"
[file4.txt]...[3] "hello hello hello hello "
[file4.txt]...[5] "hello"
[file6.txt]...[3] "hello"
是存在的代碼片段我可以添加到<過載,從而導致執行第二排序PARAM?
std :: string :: compare存在的原因是你可以有效地做這種事情。首先保存std :: string :: compare的結果。如果結果爲零,則還需要測試次要標準。但是,第一次比較的非零結果意味着第二次不需要。就像'return(c = lhs.fileName.compare(rhs.fileName))<0 || c == 0 && lhs.line
JSF