![](/img/trans.png)
[英]How to quick-sort a 1D array based on 3rd column (index divided by 3) in C++
[英]How do I sort string vectors based on 2nd column/3rd column etc?
我有一个
vector<string>data
如此组织
//NAME ID AGE
//NAME ID AGE
//NAME ID AGE
//NAME ID AGE
我可以按字母顺序按名称排序,如何根据第 2 列/第 3 列按升序对其进行排序? 感谢您的任何帮助和建议。
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);
}
您可以按每个字符读取这些字符串,直到遇到第一个/第二个空格。 然后你应该能够“过滤”出第一个/第二个属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.