c++ - 包含按值对映射进行排序的键的 vector

标签 c++ sorting dictionary vector

我有一个:

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 element w[0], w[1], etc. would contain a "link" (pointer?) to fNames's wstrings, 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/

相关文章:

c++ - 调整 QTableWidget 中列的大小

python - 在 Python 中按排序顺序从排序的迭代器中产生?

c - 如何从c中的文件中搜索元素

c - c语言冒泡排序

javascript - 用不同标签的对象中的数组汇总数组

java - 创建 MutableGuiceKeyToInstanceMap 的最简单方法?

python - 如何将 postgresql 字段名称输出到字典中,而不是仅在 python 中输出列名称?

c++ - 从 Python 调用 C++ 函数

c++ - EOF 循环在最终结束之前重复行 3 次

c++ - 文本文件 c/c++ 中的字符串用法