ENH: HashTable sorted() method

- the sorted() method fills a UPtrList with sorted entries. In some
  places this can provide a more convenient means of traversing a
  HashTable in consistent order, without the extra step of creating
  a sortedToc(). The sorted() method with a UPtrList will also have
  a lower overhead than creating any sortedToc() or toc() since it is
  list of pointers and not full copies of the keys.

  Instead of this:

      HashTable<someType> table = ...;

      for (const word& key : table.sortedToc())
      {
          Info<< key << " => " << table[key] << nl;
      }

  can write this:

      for (const auto& iter : table.sorted())
      {
          Info<< iter.key() << " => " << iter.val() << nl;
      }

STYLE:

- declare hash entry key 'const' since it is immutable
This commit is contained in:
Mark Olesen
2022-05-09 14:02:36 +02:00
parent d68902f4a7
commit 7afebef509
5 changed files with 218 additions and 82 deletions

View File

@ -6,7 +6,7 @@
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2016 OpenFOAM Foundation
Copyright (C) 2017-2021 OpenCFD Ltd.
Copyright (C) 2017-2022 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -33,7 +33,7 @@ License
#include "IOstreams.H"
#include "StringStream.H"
#include "ListOps.H"
#include "StringListOps.H"
#include "stringListOps.H"
using namespace Foam;
@ -71,9 +71,18 @@ int main()
<< "table1 [" << table1.size() << "] " << endl;
forAllConstIters(table1, iter)
{
Info<< iter.key() << " => " << iter() << nl;
Info<< iter.key() << " => " << iter.val() << nl;
}
Info<< "\ntable1 sorted() :" << endl;
for (const auto& iter : table1.sorted())
{
Info<< " " << iter.key() << " => " << iter.val() << nl;
}
Info<< endl;
table1.set("acr", 108);
table1.set("adx", 109);
table1.set("aec", 100);
@ -82,6 +91,22 @@ int main()
Info<< "\noverwrote some values table1: " << table1 << endl;
// Test writable sorted access
for (auto& iter : table1.sorted())
{
// Should not compile: iter.key() = "illegal";
iter.val() *= 2;
}
Info<< "\nInplace modified - via sorted() access :" << endl;
for (const auto& iter : table1.sorted())
{
Info<< " " << iter.key() << " => " << iter.val() << nl;
}
Info<< endl;
Info<< "\ntest find:" << endl;
Info<< table1.find("aaa")() << nl
<< table1.find("aba")() << nl