根據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

更新於: 2019年10月21日

309 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.