[英]I don't understand why my sort on a string breaks everything
I have the following code:我有以下代码:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
vector<vector<string>> findAnagrams(vector<string> wordlist) {
vector<vector<string>> result;
unordered_map<string, vector<string>*> indexes;
for (const string& word : wordlist) {
string wordSorted = word;
sort(wordSorted.begin(), wordSorted.end()); // <= This line break everything
auto index = indexes.find(wordSorted);
if (index == indexes.end()) {
vector<string> vec = { word };
result.push_back(vec);
indexes[wordSorted] = &vec;
} else {
index->second->push_back(word);
}
}
return result;
}
int main()
{
vector<string> wordlist = {"eat", "tea", "tan", "ate", "nat", "bat", "test", "estt"};
auto result = findAnagrams(wordlist);
for (const auto& vec : result) {
for (const auto& word : vec) {
cout << word << " ";
}
cout << endl;
}
return 0;
}
This code detects all anagrams in a list of given words.此代码检测给定单词列表中的所有字谜。
As my comment says, when I sort wordSorted
using std::sort
, it breaks everything and my code ends with a bad_alloc.正如我的评论所说,当我使用
std::sort
对wordSorted
进行排序时,它会破坏所有内容,并且我的代码以 bad_alloc 结尾。 As if the std::sort
manipulates the memory outside of wordSorted
.好像
std::sort
在 wordSorted 之外操纵wordSorted
。 If I remove this specific line, the code "works" (the result is obviously wrong, but it does what it should do).如果我删除这个特定的行,代码“工作”(结果显然是错误的,但它做了它应该做的)。
How it is possible?怎么可能? What am I missing?
我错过了什么?
I'm guessing these lines are the main cause of your problem:我猜这些行是你的问题的主要原因:
{
vector<string> vec = { word };
result.push_back(vec);
indexes[wordSorted] = &vec;
}
Here you store a pointer to the local variable vec
in the indexes
map.在这里,您将指向局部变量
vec
的指针存储在indexes
map 中。 When the block ends at }
the life-time of vec
also ends, and the pointer you just stored will become invalid.当块在
}
结束时, vec
的生命周期也结束了,你刚刚存储的指针将变得无效。
Any use of this pointer will lead to undefined behavior .对该指针的任何使用都会导致未定义的行为。
It seems to me that the solution is to simply not store pointers to the vector (pointers to containers are seldom, if ever, needed), and instead store a copy.在我看来,解决方案是简单地不存储指向向量的指针(指向容器的指针很少需要,如果有的话),而是存储一个副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.