How to iterate over a QHash using for_each
-
Hi!
I'm trying to iterate over a QHash using std::for_each, but I can't accomplish this task. The code I'm using:#include <QCoreApplication> #include <QHash> #include <algorithm> #include <iostream> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QHash<int, int> hash = {{1, 100}, {2, 200}, {3, 300}}; std::for_each(hash.begin(), hash.end(), [](const std::pair<const int, int>& pair) { std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl; }); return a.exec(); }
but I got error. Any ideas how to solve that ?
-
Hi!
I'm trying to iterate over a QHash using std::for_each, but I can't accomplish this task. The code I'm using:#include <QCoreApplication> #include <QHash> #include <algorithm> #include <iostream> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QHash<int, int> hash = {{1, 100}, {2, 200}, {3, 300}}; std::for_each(hash.begin(), hash.end(), [](const std::pair<const int, int>& pair) { std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl; }); return a.exec(); }
but I got error. Any ideas how to solve that ?
@Bondrusiek said in How to iterate over a QHash using for_each:
[](const std::pair<const int, int>& pair)
Change to:
[](const int &key)
See https://en.cppreference.com/w/cpp/algorithm/for_each
"Applies the given unary function object f" -
And what is the use case here? Why not use a simple for loop?
-
I have a task about that. Is it possible use for ranged loop(I also tried implement that but with error)?
-
I have a task about that. Is it possible use for ranged loop(I also tried implement that but with error)?
@Bondrusiek said in How to iterate over a QHash using for_each:
use for ranged loop
What do you mean?
If you tried something and got errors, then please post the code and the error.
-
This is a loop analogous to the one in the main thread:
for (const auto& element : hash) { std::cout << "Key: " << element.key() << " Value: " << element.value() << std::endl; }
but I suppose it's similar to the for_each loop.
-
This is a loop analogous to the one in the main thread:
for (const auto& element : hash) { std::cout << "Key: " << element.key() << " Value: " << element.value() << std::endl; }
but I suppose it's similar to the for_each loop.
@Bondrusiek Element is again the key here
-
B Bondrusiek has marked this topic as solved
-
I have a task about that. Is it possible use for ranged loop(I also tried implement that but with error)?
@Bondrusiek if you want to have access to the key and value, you need to use keyValueBegin and keyValueEnd.
QHash doesn't match the stl API but it was too late to change when it was discovered.