第二章 问题C:变位词 #include "stdafx.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <algorithm> using namespace std; /************************************************************************/ /* 构造的结构体:sign为字符串str的签名 */ /************************************************************************/ struct CombineStr { string sign; string str; bool operator < (const CombineStr &other) { return (sign < other.sign); } }; /************************************************************************/ /* 函数功能:输出CombineStr */ /************************************************************************/ void print(const CombineStr &other) { cout<<other.sign<<" "<<other.str<<endl; } /************************************************************************/ /* 函数功能:qsrot的比较函数 */ /************************************************************************/ int cmp(const void *lhs, const void *rhs) { return *((char*)lhs) - *((char*)rhs); } /************************************************************************/ /* 函数功能:取得字符串str的签名 */ /************************************************************************/ string getSign(string str) { const char *pStr = str.c_str(); int len = strlen(pStr); char *temp = new char[len + 1]; strcpy(temp, pStr); qsort(temp, len, sizeof(char), cmp); return string(temp); } int main() { ifstream file("input.txt"); vector<CombineStr> vec; string readStr; CombineStr combinstr; while (!file.eof()) { file>>readStr; combinstr.sign = getSign(readStr); combinstr.str = readStr; vec.push_back(combinstr); } sort(vec.begin(), vec.end()); //对vec进行排序 for_each(vec.begin(), vec.end(), print); cout<<"输出结果为:"<<endl; vector<CombineStr>::iterator iter = vec.begin(); while(iter != vec.end()) { string oldSign = iter->sign; while ((iter != vec.end())&& (iter->sign == oldSign)) { cout<<iter->str<<" "; iter++; } cout<<endl; } } 其实:可是使用multimap来简化程序。