我有一个:
std::map<long, std::wstring> fNames; // ex: fNames[FileReferenceNumber] = L"hello.txt"
作为std::map
有有序的键,但没有值(哈希表 unordered_map
甚至没有有序),我想创建一个 vector :
std::vector<long> v;
将包含键以允许迭代fNames
按值排序。
例子:如果我们有
9187 => "hello.txt"
13 => "z.txt"
1777 => "a.txt"
然后 v
将是:[1777, 9187, 13]
, 允许迭代 fNames
按值排序:
for (int i = 0; i < v.size(); i++)
wcout << fNames[v[i]]; // a.txt, hello.txt, z.txt
有没有办法创建这个 vector v
通过使用 std::sort
?我不知道怎么办。我应该使用自定义谓词吗?
PS:更好的是:是否可以生成 std::vector<wstring> w
排序?即每个元素 w[0]
, w[1]
等将包含指向 fNames
的“链接”(指针?)的 wstrings,但不是拷贝(以避免重复字符串数据)?
或者可能是 std::vector<wchar_t *> w
?
最佳答案
PS: Even better: would it be possible to produce a
std::vector<wstring> w
sorted? i.e. each elementw[0]
,w[1]
, etc. would contain a "link" (pointer?) tofNames
'swstring
s, but not a copy (to avoid duplicating the string data)?
A vector<wstring>
将包含重复的字符串(因为 CoW - 写时复制 - 自 C++11 起禁止用于 std::[w]string
)。如果你想使用 const wchar_t*
为避免字符串重复,您可以这样做:
vector<const wchar_t*> sortedFilenames;
// Reserve room in the vector, since we know how many strings to add
sortedFilenames.reserve(fNames.size());
// Add string pointers from map to vector
for (const auto& e : fNames) {
// Avoid duplicates using const wchar_t*
sortedFilenames.push_back(e.second.c_str());
}
// Sort the string vector
sort(begin(sortedFilenames), end(sortedFilenames),
[](const auto& p1, const auto& p2) {
// Use whatever sorting rule you need here...
return wcscmp(p1, p2) < 0;
}
);
编辑 根据您的评论,您可以使用 vector<const wstring*>
同样,例如:
vector<const wstring*> sortedFilenames;
// Reserve room in the vector, since we know how many strings to add
sortedFilenames.reserve(fNames.size());
// Add string pointers from map to vector
for (const auto& e : fNames) {
sortedFilenames.push_back(&(e.second));
}
// Sort the string vector
sort(begin(sortedFilenames), end(sortedFilenames),
[](const auto& p1, const auto& p2) {
return (*p1) < (*p2); // or whatever sorting rule...
}
);
关于c++ - 包含按值对映射进行排序的键的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45443268/