1 // Copyright 2010-2021 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #ifndef OR_TOOLS_UTIL_STRING_ARRAY_H_
15 #define OR_TOOLS_UTIL_STRING_ARRAY_H_
16 
17 #include <string>
18 #include <vector>
19 
20 namespace operations_research {
21 // ---------- Pretty Print Helpers ----------
22 
23 // See the straightforward (and unique) usage of this macro below.
24 #define RETURN_STRINGIFIED_VECTOR(vector, separator, method) \
25   std::string out;                                           \
26   for (int i = 0; i < vector.size(); ++i) {                  \
27     if (i > 0) out += separator;                             \
28     out += vector[i] method;                                 \
29   }                                                          \
30   return out
31 
32 // Converts a vector into a string by calling the given method (or simply
33 // getting the given string member), on all elements, and concatenating
34 // the obtained strings with the given separator.
35 
36 // Join v[i].DebugString().
37 template <class T>
JoinDebugString(const std::vector<T> & v,const std::string & separator)38 std::string JoinDebugString(const std::vector<T>& v,
39                             const std::string& separator) {
40   RETURN_STRINGIFIED_VECTOR(v, separator, .DebugString());
41 }
42 
43 // Join v[i]->DebugString().
44 template <class T>
JoinDebugStringPtr(const std::vector<T> & v,const std::string & separator)45 std::string JoinDebugStringPtr(const std::vector<T>& v,
46                                const std::string& separator) {
47   RETURN_STRINGIFIED_VECTOR(v, separator, ->DebugString());
48 }
49 
50 // Join v[i]->name().
51 template <class T>
JoinNamePtr(const std::vector<T> & v,const std::string & separator)52 std::string JoinNamePtr(const std::vector<T>& v, const std::string& separator) {
53   RETURN_STRINGIFIED_VECTOR(v, separator, ->name());
54 }
55 
56 // Join v[i]->name.
57 template <class T>
JoinNameFieldPtr(const std::vector<T> & v,const std::string & separator)58 std::string JoinNameFieldPtr(const std::vector<T>& v,
59                              const std::string& separator) {
60   RETURN_STRINGIFIED_VECTOR(v, separator, ->name);
61 }
62 
63 #undef RETURN_STRINGIFIED_VECTOR
64 
65 }  // namespace operations_research
66 #endif  // OR_TOOLS_UTIL_STRING_ARRAY_H_
67