【发布时间】:2013-10-15 09:00:42
【问题描述】:
此代码是此处代码的轻微修改:Given a string array, return all groups of strings that are anagrams
最近1小时看了map、set等文章的参考文献还是看不懂。
#include <map>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main(){
int n; cin >>n;
string word;
map<string, set<string> > anagrams;
for (int i=0;i<n;i++){
cin >> word;
string sortedWord(word);
sort(sortedWord.begin(), sortedWord.end());
anagrams[sortedWord].insert(word);
}
for (auto& pair : anagrams){
for (auto& word: pair.second){
cout << word << " ";
}
//cout << "\n";
}
}
据我了解,set 更像是一个有序向量。所以当我们来到这行代码时
anagrams[sortedWord].insert(word);
它使用我们的 sortedWord 作为键并将该对插入到字谜中。现在,当我继续插入对时,字谜会根据 sortedWord 自动排序。因此,例如,如果我按此顺序插入 cat、god、act,则字谜将包含:
act act
act cat
dgo god
现在,当我使用基于范围的循环时,它会打印这对的第二项。我的理解正确吗? 我有两个问题。当我们使用 sortedWord 作为键时,它为什么不替换之前的值呢?例如,act cat 应该替换 act act。这是因为地图或集合的实施吗?第二个问题,当我尝试为以下输入打印 pair.first 时,我得到了一些随机输出:
Input:
5
cat act dog tac god
Output(for pair.second):
act cat tac dog god
Output(for pair.first):
a c t d g o
如果有人能给我进一步使用 set,我将不胜感激。
【问题讨论】:
-
pair.first 是一个 std::string 所以基于范围的 for 循环告诉你每个字母
-
@SJuan76:
std::set中的顺序并不重要。没有顺序的集合是std::unordered_set。