Use range-based for loops (C++11) when looping over map elements #10493

pull practicalswift wants to merge 1 commits into bitcoin:master from practicalswift:map changing 13 files +74 −74
  1. practicalswift commented at 4:20 AM on June 1, 2017: contributor

    Before this commit:

    for (std::map<T1, T2>::iterator x = y.begin(); x != y.end(); ++x) {
        T1 z = (*x).first;
        …
    }
    

    After this commit:

    for (auto& x : y) {
        T1 z = x.first;
        …
    }
    
  2. fanquake added the label Refactoring on Jun 1, 2017
  3. dcousens approved
  4. dcousens commented at 4:37 AM on June 1, 2017: contributor

    utACK

  5. practicalswift force-pushed on Jun 1, 2017
  6. practicalswift renamed this:
    Use range-based for loops (C+11) when looping over map elements
    Use range-based for loops (C++11) when looping over map elements
    on Jun 1, 2017
  7. in src/addrman.cpp:394 in cf2a6df933 outdated
     389 | @@ -390,7 +390,7 @@ int CAddrMan::Check_()
     390 |      if (vRandom.size() != nTried + nNew)
     391 |          return -7;
     392 |  
     393 | -    for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++) {
     394 | +    for (auto& it : mapInfo) {
     395 |          int n = (*it).first;
    


    benma commented at 8:41 AM on June 1, 2017:

    Should be it.first and it.second.

  8. practicalswift force-pushed on Jun 1, 2017
  9. practicalswift commented at 9:24 AM on June 1, 2017: contributor

    @benma Thanks for reviewing! Fixed! :-)

  10. benma commented at 9:26 AM on June 1, 2017: none

    utACK cf02bb1a6c3c0077f1cf37f60e13d6cb71fd9187

  11. practicalswift force-pushed on Jun 4, 2017
  12. practicalswift commented at 2:54 PM on June 4, 2017: contributor

    Rebased!

  13. practicalswift force-pushed on Jun 4, 2017
  14. sipa commented at 6:27 PM on June 4, 2017: member

    Overall comment: the loop variables should probably not keep the name it, as that may confuse someone into thinking it refers to an iterator, while it is a container element reference.

  15. practicalswift commented at 6:54 PM on June 4, 2017: contributor

    @sipa Good point! Any suggestion on an appropriate generic variable name to use instead? Perhaps pair in the case of maps or o otherwise?

  16. sipa commented at 6:59 PM on June 4, 2017: member

    @practicalswift Perhaps entry for maps?

  17. practicalswift commented at 7:00 PM on June 4, 2017: contributor

    @sipa Ah, yes, entry is much better. Fixing it now!

  18. practicalswift force-pushed on Jun 4, 2017
  19. practicalswift force-pushed on Jun 4, 2017
  20. practicalswift commented at 8:27 PM on June 4, 2017: contributor

    @sipa Fixed! :-)

  21. in src/rpc/net.cpp:570 in 5551e3586b outdated
     566 | @@ -567,11 +567,11 @@ UniValue listbanned(const JSONRPCRequest& request)
     567 |      g_connman->GetBanned(banMap);
     568 |  
     569 |      UniValue bannedAddresses(UniValue::VARR);
     570 | -    for (banmap_t::iterator it = banMap.begin(); it != banMap.end(); it++)
     571 | +    for (auto& entry : banMap)
    


    MarcoFalke commented at 8:15 PM on June 5, 2017:

    Since you are touching all those lines anyway, you can change them to const references for free. Something like the following diff should do:

    diff --git a/src/addrdb.h b/src/addrdb.h
    index c3d509b..e0a49c8 100644
    --- a/src/addrdb.h
    +++ b/src/addrdb.h
    @@ -61,7 +61,7 @@ public:
             banReason = BanReasonUnknown;
         }
     
    -    std::string banReasonToString()
    +    std::string banReasonToString() const
         {
             switch (banReason) {
             case BanReasonNodeMisbehaving:
    diff --git a/src/addrman.cpp b/src/addrman.cpp
    index 0edf111..2f7c014 100644
    --- a/src/addrman.cpp
    +++ b/src/addrman.cpp
    @@ -390,9 +390,9 @@ int CAddrMan::Check_()
         if (vRandom.size() != nTried + nNew)
             return -7;
     
    -    for (auto& entry : mapInfo) {
    +    for (const auto& entry : mapInfo) {
             int n = entry.first;
    -        CAddrInfo& info = entry.second;
    +        const CAddrInfo& info = entry.second;
             if (info.fInTried) {
                 if (!info.nLastSuccess)
                     return -1;
    diff --git a/src/net.cpp b/src/net.cpp
    index e6c5da8..c071fec 100644
    --- a/src/net.cpp
    +++ b/src/net.cpp
    @@ -106,7 +106,7 @@ bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
         int nBestReachability = -1;
         {
             LOCK(cs_mapLocalHost);
    -        for (auto& entry : mapLocalHost)
    +        for (const auto& entry : mapLocalHost)
             {
                 int nScore = entry.second.nScore;
                 int nReachability = entry.first.GetReachabilityFrom(paddrPeer);
    @@ -472,10 +472,10 @@ bool CConnman::IsBanned(CNetAddr ip)
         bool fResult = false;
         {
             LOCK(cs_setBanned);
    -        for (auto& entry : setBanned)
    +        for (const auto& entry : setBanned)
             {
    -            CSubNet subNet = entry.first;
    -            CBanEntry banEntry = entry.second;
    +            const CSubNet& subNet = entry.first;
    +            const CBanEntry& banEntry = entry.second;
     
                 if(subNet.Match(ip) && GetTime() < banEntry.nBanUntil)
                     fResult = true;
    diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp
    index 5b75886..99c2475 100644
    --- a/src/qt/transactiontablemodel.cpp
    +++ b/src/qt/transactiontablemodel.cpp
    @@ -82,7 +82,7 @@ public:
             cachedWallet.clear();
             {
                 LOCK2(cs_main, wallet->cs_wallet);
    -            for (auto& entry : wallet->mapWallet)
    +            for (const auto& entry : wallet->mapWallet)
                 {
                     if (TransactionRecord::showTransaction(entry.second))
                         cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, entry.second));
    diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp
    index 85df33a..345befd 100644
    --- a/src/rpc/net.cpp
    +++ b/src/rpc/net.cpp
    @@ -570,9 +570,9 @@ UniValue listbanned(const JSONRPCRequest& request)
         g_connman->GetBanned(banMap);
     
         UniValue bannedAddresses(UniValue::VARR);
    -    for (auto& entry : banMap)
    +    for (const auto& entry : banMap)
         {
    -        CBanEntry banEntry = entry.second;
    +        const CBanEntry& banEntry = entry.second;
             UniValue rec(UniValue::VOBJ);
             rec.push_back(Pair("address", entry.first.ToString()));
             rec.push_back(Pair("banned_until", banEntry.nBanUntil));
    diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp
    index db39ac6..6ee1f7d 100644
    --- a/src/test/coins_tests.cpp
    +++ b/src/test/coins_tests.cpp
    @@ -88,7 +88,7 @@ public:
             // Manually recompute the dynamic usage of the whole data, and compare it.
             size_t ret = memusage::DynamicUsage(cacheCoins);
             size_t count = 0;
    -        for (auto& entry : cacheCoins) {
    +        for (const auto& entry : cacheCoins) {
                 ret += entry.second.coin.DynamicMemoryUsage();
                 ++count;
             }
    @@ -182,7 +182,7 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
     
             // Once every 1000 iterations and at the end, verify the full cache.
             if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
    -            for (auto& entry : result) {
    +            for (const auto& entry : result) {
                     bool have = stack.back()->HaveCoin(entry.first);
                     const Coin& coin = stack.back()->AccessCoin(entry.first);
                     BOOST_CHECK(have == !coin.IsSpent());
    @@ -413,7 +413,7 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
     
             // Once every 1000 iterations and at the end, verify the full cache.
             if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
    -            for (auto& entry : result) {
    +            for (const auto& entry : result) {
                     bool have = stack.back()->HaveCoin(entry.first);
                     const Coin& coin = stack.back()->AccessCoin(entry.first);
                     BOOST_CHECK(have == !coin.IsSpent());
    diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp
    index a5143aa..e85732e 100644
    --- a/src/wallet/rpcwallet.cpp
    +++ b/src/wallet/rpcwallet.cpp
    @@ -1263,7 +1263,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
     
         if (fByAccounts)
         {
    -        for (auto& entry : mapAccountTally)
    +        for (const auto& entry : mapAccountTally)
             {
                 CAmount nAmount = entry.second.nAmount;
                 int nConf = entry.second.nConf;
    
  22. practicalswift force-pushed on Jun 7, 2017
  23. practicalswift commented at 6:53 PM on June 7, 2017: contributor

    @MarcoFalke Good idea! You're suggestions are now part of the PR :-)

  24. practicalswift force-pushed on Jun 8, 2017
  25. practicalswift commented at 8:46 AM on June 8, 2017: contributor

    Merge conflicts resolved!

  26. sipa commented at 12:36 AM on June 13, 2017: member

    Needs rebase

  27. practicalswift force-pushed on Jun 13, 2017
  28. practicalswift commented at 7:35 AM on June 13, 2017: contributor

    Rebased!

  29. jtimon commented at 10:08 PM on July 18, 2017: contributor

    utACK 875ebee20e048892d999c41acb7100d0fdac1f91

  30. in src/qt/bantablemodel.cpp:58 in 875ebee20e outdated
      54 | @@ -55,11 +55,11 @@ class BanTablePriv
      55 |  #if QT_VERSION >= 0x040700
      56 |          cachedBanlist.reserve(banMap.size());
      57 |  #endif
      58 | -        for (banmap_t::iterator it = banMap.begin(); it != banMap.end(); it++)
      59 | +        for (auto& entry : banMap)
    


    sipa commented at 12:22 AM on July 19, 2017:

    I think this can be const

  31. in src/validation.cpp:3123 in 875ebee20e outdated
    3119 | @@ -3120,8 +3120,8 @@ static uint64_t CalculateCurrentUsage()
    3120 |  /* Prune a block file (modify associated database entries)*/
    3121 |  void PruneOneBlockFile(const int fileNumber)
    3122 |  {
    3123 | -    for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
    3124 | -        CBlockIndex* pindex = it->second;
    3125 | +    for (auto& entry : mapBlockIndex) {
    


    sipa commented at 12:25 AM on July 19, 2017:

    Can be const (the loop modifies the entries pointed to by mapBlockIndex, not the entries directly.

  32. in src/validation.cpp:3573 in 875ebee20e outdated
    3569 | @@ -3570,8 +3570,8 @@ bool RewindBlockIndex(const CChainParams& params)
    3570 |      // Reduce validity flag and have-data flags.
    3571 |      // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
    3572 |      // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
    3573 | -    for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
    3574 | -        CBlockIndex* pindexIter = it->second;
    3575 | +    for (auto& entry : mapBlockIndex) {
    


    sipa commented at 12:25 AM on July 19, 2017:

    Same, can be const.

  33. sipa commented at 12:27 AM on July 19, 2017: member

    I believe there may be a few more possible consts missing.

  34. practicalswift force-pushed on Jul 19, 2017
  35. practicalswift force-pushed on Jul 19, 2017
  36. practicalswift commented at 2:09 PM on July 19, 2017: contributor

    @sipa Thanks! const:s added :-)

  37. promag commented at 2:27 PM on July 19, 2017: member

    You are missing reverse iteration. For instance, https://github.com/bitcoin/bitcoin/blob/master/src/wallet/wallet.cpp#L3722.

    Edit, fwiw, see reverse_iterator.h.

  38. practicalswift commented at 2:38 PM on July 19, 2017: contributor

    @promag Not part of the scope of this PR :-)

  39. promag commented at 3:51 PM on July 19, 2017: member

    @practicalswift commit message suggests otherwise, range based loop over map entries regardless of direction.

    Edit: is it bad to include the missing reverse iterations?

  40. practicalswift commented at 4:20 PM on July 19, 2017: contributor

    @promag Is it these two you are referring to?

    src/wallet/rpcwallet.cpp:    for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
    src/wallet/wallet.cpp:            for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
    
  41. promag commented at 8:27 PM on July 19, 2017: member

    Yes, they are multimap, but still a map. IMO it makes sense to also replace those for range loop.

  42. jtimon commented at 8:39 PM on July 19, 2017: contributor

    You can use reverse_iterate() for those.

  43. promag commented at 8:44 PM on July 19, 2017: member

    @jtimon that was my suggestion.

  44. practicalswift force-pushed on Aug 14, 2017
  45. practicalswift commented at 3:33 PM on August 14, 2017: contributor

    Rebased!

  46. jtimon commented at 3:50 PM on August 14, 2017: contributor

    fast review ACK

  47. practicalswift force-pushed on Aug 16, 2017
  48. practicalswift commented at 2:22 PM on August 16, 2017: contributor

    Rebased!

  49. practicalswift force-pushed on Aug 16, 2017
  50. sipa referenced this in commit 98212745c8 on Sep 20, 2017
  51. Use range-based for loops (C++11) when looping over map elements
    Before this commit:
    
      for (std::map<T1, T2>::iterator x = y.begin(); x != y.end(); ++x) {
      }
    
    After this commit:
    
      for (auto& x : y) {
      }
    680bc2cbb3
  52. practicalswift force-pushed on Oct 9, 2017
  53. practicalswift commented at 7:33 PM on October 9, 2017: contributor

    Rebased again! Anyone willing to re-review? I think this one should be ready for merge :-)

  54. jtimon commented at 8:11 AM on October 10, 2017: contributor

    fast review re-ACK

  55. practicalswift commented at 9:32 AM on October 10, 2017: contributor

    @promag What about it? :-)

  56. promag commented at 12:45 PM on October 10, 2017: member

    @practicalswift use range-based there too?

  57. practicalswift commented at 3:54 PM on October 10, 2017: contributor

    @promag Yes, but with an additional condition (account.vchPubKey.IsValid()). The scope of this PR is to cover the simplest possible case only (for (std::map<T1, T2>::iterator x = y.begin(); x != y.end(); ++x) {) to make reviewing trivial.

  58. ajtowns approved
  59. ajtowns commented at 7:40 AM on October 11, 2017: member

    TestedACK 680bc2cbb34d6bedd0e64b17d0555216572be4c8. Looks good to me. There's a bunch of untouched for()'s with vector::iterator and set::iterator's that could presumably have similar refactors in a later commit.

  60. practicalswift commented at 8:06 AM on October 11, 2017: contributor

    @ajtowns Thanks for the review and the tested ACK! This PR is intentionally only touching std::map to limit the scope and make it easy to review :-)

  61. practicalswift commented at 7:17 PM on November 21, 2017: contributor

    Does this PR stand a chance of being merged? If not I'll close it :-)

  62. sipa commented at 2:15 AM on November 22, 2017: member

    utACK 680bc2cbb34d6bedd0e64b17d0555216572be4c8

  63. MarcoFalke commented at 4:41 PM on November 22, 2017: member

    utACK 680bc2cbb34d6bedd0e64b17d0555216572be4c8

  64. practicalswift commented at 7:12 AM on November 30, 2017: contributor

    Ready for merge? :-)

  65. MarcoFalke merged this on Nov 30, 2017
  66. MarcoFalke closed this on Nov 30, 2017

  67. MarcoFalke referenced this in commit fbce66a982 on Nov 30, 2017
  68. PastaPastaPasta referenced this in commit 1eebe9f66a on Dec 22, 2019
  69. PastaPastaPasta referenced this in commit f3b1eb4f45 on Jan 2, 2020
  70. PastaPastaPasta referenced this in commit dfc8635268 on Jan 4, 2020
  71. PastaPastaPasta referenced this in commit dc75e25549 on Jan 12, 2020
  72. PastaPastaPasta referenced this in commit d702ae8ac4 on Jan 12, 2020
  73. PastaPastaPasta referenced this in commit 4a876991af on Jan 12, 2020
  74. PastaPastaPasta referenced this in commit 6cf675807e on Jan 12, 2020
  75. PastaPastaPasta referenced this in commit f3d7d1bf4c on Mar 27, 2020
  76. PastaPastaPasta referenced this in commit e4517fd9b3 on Mar 28, 2020
  77. PastaPastaPasta referenced this in commit 2f217116cb on Mar 29, 2020
  78. PastaPastaPasta referenced this in commit c270aa81cd on Mar 31, 2020
  79. UdjinM6 referenced this in commit 7801f94603 on Mar 31, 2020
  80. PastaPastaPasta referenced this in commit a98db86ada on Apr 1, 2020
  81. ckti referenced this in commit d917fb7e68 on Mar 28, 2021
  82. ckti referenced this in commit ef12c2946c on Mar 28, 2021
  83. practicalswift deleted the branch on Apr 10, 2021
  84. gades referenced this in commit 3d3779221d on Jun 25, 2021
  85. gades referenced this in commit b95b4443f5 on Jun 26, 2021
  86. furszy referenced this in commit 60d36292bc on Jul 26, 2021
  87. gades referenced this in commit 3821b42db4 on Jan 28, 2022
  88. gades referenced this in commit c9e19c558a on Feb 9, 2022
  89. DrahtBot locked this on Aug 18, 2022

github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-04-16 15:15 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me