根据C ++中另一个字符串定义的字母顺序对字符串数组进行排序

假设我们有一个字符串数组,还有另一个字符串供参考。我们必须获取参考字符串,并使用参考字符串中字符的顺序对字符串数组进行排序。在这里,我们考虑数组中的字符串,并且参考字符串使用小写字母。

假设字符串数组类似:[“ hello”,“ programming”,“ science”,“ computer”,“ india”],参考字符串类似:“ pigvxbskyhqzelutoacfjrndmw”,排序后的输出字符串将类似于[“ programming ”,“印度”,“科学”,“你好”,“计算机”]

任务很简单。我们必须遍历参考字符串,然后将字符作为键存储在映射中,并将索引存储为值。现在要对字符串进行排序,我们必须根据该映射而不是ASCII字符顺序来比较字符串。比较映射到映射中那些特定字符的值,如果字符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