根据C++中另一个字符串定义的字母顺序对字符串数组进行排序
假设我们有一个字符串数组,还有一个字符串作为参考。我们需要获取参考字符串,并使用参考字符串中字符的顺序对字符串数组进行排序。这里我们考虑数组中的字符串,参考字符串都是小写字母。
假设字符串数组如下: [“hello”, “programming”, “science”, “computer”, “india”],参考字符串如下:“pigvxbskyhqzelutoacfjrndmw”,排序后的输出字符串将如下:[“programming”, “india”, “science”, “hello”, “computer”]
任务很简单。我们需要遍历参考字符串,然后将字符存储到map中作为键,索引作为值。现在要对字符串进行排序,我们需要根据该map而不是ASCII字符顺序来比较字符串。比较map中映射到这些特定字符的值,如果字符c1出现在c2之前,则c1 < c2。
示例
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
unordered_map<char, int> char_map;
bool compare(string c1, string c2) {
for (int i = 0; i < min(c1.size(), c2.size()); i++) {
if (char_map[c1[i]] == char_map[c2[i]])
continue;
return char_map[c1[i]] < char_map[c2[i]];
}
return c1.size() < c2.size();
}
int main() {
string str = "pigvxbskyhqzelutoacfjrndmw";
vector<string> v{ "hello", "programming", "science", "computer", "india" };
char_map.clear();
for (int i = 0; i < str.size(); i++)
char_map[str[i]] = i;
sort(v.begin(), v.end(), compare);
// Print the strings after sorting
for (auto x : v)
cout << x << " ";
}输出
programming india science hello computer
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP