Add helper function to make a vector from an ArrayRef
authorMark Abraham <mark.j.abraham@gmail.com>
Tue, 6 Mar 2018 09:53:19 +0000 (10:53 +0100)
committerMark Abraham <mark.j.abraham@gmail.com>
Tue, 20 Mar 2018 06:44:49 +0000 (07:44 +0100)
This syntactic sugar makes it easy to make a vector with a copy of the
contents.

Change-Id: Ib51c8a1d88aee7ca35fe1715d6f094b60e90e0b2

src/gromacs/gmxana/gmx_eneconv.cpp
src/gromacs/gmxana/gmx_trjcat.cpp
src/gromacs/utility/arrayref.h

index a84f667b672131cc10b11e6497f876096f390796..6b089b1dd3889be18b63c708edb21254357af8f7 100644 (file)
@@ -510,8 +510,7 @@ int gmx_eneconv(int argc, char *argv[])
     lastfilestep = 0;
     laststep     = 0;
 
-    gmx::ArrayRef<const std::string> filesOrig = opt2fns("-f", NFILE, fnm);
-    std::vector<std::string>         files(filesOrig.begin(), filesOrig.end());
+    auto files = gmx::copyOf(opt2fns("-f", NFILE, fnm));
 
     if (files.empty())
     {
index a2b694ed1b67b3a7c42a71e05b7877e2e0316b40..f6ecb4f2445f2b8db4141409c55015b472d67413 100644 (file)
@@ -585,7 +585,7 @@ int gmx_trjcat(int argc, char *argv[])
     }
     if (bDeMux)
     {
-        std::vector<std::string> outFilesDemux(outFiles.begin(), outFiles.end());
+        auto outFilesDemux = gmx::copyOf(outFiles);
         if (static_cast<int>(outFilesDemux.size()) != nset)
         {
             std::string name = outFilesDemux[0];
@@ -605,7 +605,7 @@ int gmx_trjcat(int argc, char *argv[])
 
         snew(settime, inFiles.size() + 1);
         snew(cont_type, inFiles.size() + 1);
-        std::vector<std::string> inFilesEdited(inFiles.begin(), inFiles.end());
+        auto inFilesEdited = gmx::copyOf(inFiles);
         edit_files(inFilesEdited, readtime, timest, settime, cont_type, bSetTime, bSort,
                    oenv);
 
index 193134d8f01f0c35230cb0184b8f33364493ec2b..bc1191da16fc0f2dbdb43a532a122d172ec48959 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * This file is part of the GROMACS molecular simulation package.
  *
- * Copyright (c) 2012,2013,2014,2015,2016,2017, by the GROMACS development team, led by
+ * Copyright (c) 2012,2013,2014,2015,2016,2017,2018, by the GROMACS development team, led by
  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
  * and including many others, as listed in the AUTHORS file in the
  * top-level source directory and at http://www.gromacs.org.
@@ -316,6 +316,22 @@ void swap(ArrayRef<T> &a, ArrayRef<T> &b)
     a.swap(b);
 }
 
+/*! \brief Return a vector that is a copy of an ArrayRef.
+ *
+ * This makes it convenient, clear, and performant (the compiler will
+ * either do RVO to elide the temporary, or invoke the move constructor
+ * taking the unnamed temporary) to write a declaration like
+ *
+ *   auto v = copyOf(arrayRef);
+ *
+ * \ingroup module_utility
+ */
+template <typename T>
+std::vector<T> copyOf(const ArrayRef<const T> &arrayRef)
+{
+    return std::vector<T>(arrayRef.begin(), arrayRef.end());
+}
+
 } // namespace gmx
 
 #endif