如何根据第二列/第三列等对字符串向量进行排序?

How do I sort string vectors based on 2nd column/3rd column etc?

本文关键字:字符串 向量 排序 何根 二列 三列      更新时间:2023-10-16

我有一个

vector<string>data

这样组织

//NAME ID AGE
//NAME ID AGE
//NAME ID AGE
//NAME ID AGE

我可以按名称字母顺序排序,如何根据第二列/第三列按升序排序?感谢您的任何帮助和建议。

std::sort的第三个重载有第三个参数,允许你提供一个函数来执行排序逻辑。

// get nth token from a string
std::string getnTh(const std::string & str, int n)
{
std::istringstream strm(str);
std::string result;
for (int count = 0; count < n; count++)
{
if (!(strm >> result))
{
throw std::out_of_range("ran out of tokens before n");
}
}
return result;
}
// get ID, second token, from string
std::string get_ID(const std::string str)
{
return getnTh(str, 2);
}
// compare the ID field, second token,  in two strings
bool cmp_ID(const std::string &a, const std::string &b)
{
std::string tokena = get_ID(a);
std::string tokenb = get_ID(b);
return tokena < tokenb;
}
int main()
{
std::vector<std::string> data {"c c c ", "b b b " , "a a a"};
std::sort (data.begin(), data.end(), cmp_ID);
}

注意:此代码可以稍微压缩一下。为了便于阅读,我逐步分解了它。

注意:这太残酷了!它不断地一遍又一遍地解析相同的string,这是一种令人作呕的浪费精力。

相反,您应该创建一个结构来存储已解析的字符串并将该结构存储在std::vector中。

// stores a person
struct person
{
std::string name;
std::string ID;
std::string age;
// constructor to parse an input string into a new person
person(const std::string & in)
{
std::istringstream strm(in);
if (!(strm >> name >> ID >> age))
{
throw std::runtime_error("invalid person input");
}
}
};
// much simpler and faster compare function. All of the parsing is done once ahead of time.
bool cmp_ID(const person &a, const person &b)
{
return a.ID < b.ID;
}
int main()
{
// replaces vector<string> data
std::vector<person> data {{"c c c"}, {"b b b"} , {"a a a"}};
std::sort (data.begin(), data.end(), cmp_ID);
}

您可以按每个字符读取这些字符串,直到您点击第一个/第二个空格。 然后,您应该能够"过滤"出第一个/第二个属性。