#include <iostream> #include <string.h> //#include <map> #include <vector> #include <algorithm> using namespace std; bool cmp(const pair<int, char>&P1, const pair<int, char>&P2) { if(P1.second==P2.second) { return P1.first<P2.first;//不知道return p1.second<=p2.second为啥不行 } return P1.second < P2.second; } int main() { string str; //string temp; while (cin>>str) { vector<pair<int,char>>v; //map<int,char>m; for(int i = 0;i<str.length();i++) { if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')) { pair<int,char>temp; char ch = str[i]; temp.first=i;//位置 temp.second=tolower(ch); //m[i]=tolower(str[i]); v.push_back(temp); } } sort(v.begin(),v.end(),cmp);//把出现的是字母的位置排序一手 int j = 0; for(int i = 0;i <str.length();i++) { //输出排序后的字母或者原字符 if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')) { cout<<str[v[j].first]; j++; continue; } cout<<str[i]; } cout<<endl; } return 0; }
然后突然想起来存的又不是map换个位置可以直接排的
#include <iostream> #include <string.h> //#include <map> #include <vector> #include <algorithm> using namespace std; /* bool cmp(const pair<int, char>&P1, const pair<int, char>&P2) { if(P1.second==P2.second) { return P1.first<P2.first;//不知道return p1.second<=p2.second为啥不行 } return P1.second < P2.second; } */ int main() { string str; //string temp; while (cin>>str) { vector<pair<char,int>>v; //map<int,char>m; for(int i = 0;i<str.length();i++) { if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')) { pair<char,int>temp; char ch = str[i]; temp.second=i; temp.first=tolower(ch); //m[i]=tolower(str[i]); v.push_back(temp); } } sort(v.begin(),v.end()); int j = 0; for(int i = 0;i <str.length();i++) { if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')) { cout<<str[v[j].second]; j++; continue; } cout<<str[i]; } cout<<endl; } return 0; }