From f0bb0d2262360fff08a6f9a7a46e033cdecd03e9 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Mon, 17 Dec 2018 23:29:33 -0500 Subject: [PATCH] Make AnyMap iterable --- include/cantera/base/AnyMap.h | 14 ++++++++++++++ src/base/AnyMap.cpp | 8 ++++++++ test/general/test_containers.cpp | 18 ++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/include/cantera/base/AnyMap.h b/include/cantera/base/AnyMap.h index 7cf2fbe4f..81a6ee91c 100644 --- a/include/cantera/base/AnyMap.h +++ b/include/cantera/base/AnyMap.h @@ -229,6 +229,16 @@ public: const std::string& getString(const std::string& key, const std::string& default_) const; + // Define begin() and end() to allow use with range-based for loops + using const_iterator = std::unordered_map::const_iterator; + const_iterator begin() const { + return m_data.begin(); + } + + const_iterator end() const { + return m_data.end(); + } + private: template const T& get(const std::string& key, const T& default_, @@ -238,6 +248,10 @@ private: friend class AnyValue; }; +// Define begin() and end() to allow use with range-based for loops +AnyMap::const_iterator begin(const AnyValue& v); +AnyMap::const_iterator end(const AnyValue& v); + } #ifndef CANTERA_API_NO_BOOST diff --git a/src/base/AnyMap.cpp b/src/base/AnyMap.cpp index 45b13319d..def12bacd 100644 --- a/src/base/AnyMap.cpp +++ b/src/base/AnyMap.cpp @@ -606,4 +606,12 @@ AnyMap AnyMap::fromYamlFile(const std::string& name) { return node.as(); } +AnyMap::const_iterator begin(const AnyValue& v) { + return v.as().begin(); +} + +AnyMap::const_iterator end(const AnyValue& v) { + return v.as().end(); +} + } diff --git a/test/general/test_containers.cpp b/test/general/test_containers.cpp index 134bc9ade..02ce1eab5 100644 --- a/test/general/test_containers.cpp +++ b/test/general/test_containers.cpp @@ -150,6 +150,24 @@ TEST(AnyMap, conversion_to_anyvalue) EXPECT_EQ(n.at("strings").asVector()[0].asString(), "foo"); } +TEST(AnyMap, iterators) +{ + AnyMap m = AnyMap::fromYamlString( + "{a: 1, b: two, c: 3.01, d: {foo: 1, bar: 2}}"); + std::vector keys; + for (const auto& item : m) { + keys.push_back(item.first); + } + EXPECT_EQ(keys.size(), (size_t) 4); + EXPECT_TRUE(std::find(keys.begin(), keys.end(), "c") != keys.end()); + keys.clear(); + + for (const auto& item : m.at("d")) { + keys.push_back(item.first); + } + EXPECT_EQ(keys.size(), (size_t) 2); + EXPECT_TRUE(std::find(keys.begin(), keys.end(), "bar") != keys.end()); +} TEST(AnyMap, loadYaml) {