-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.hpp
More file actions
82 lines (67 loc) · 1.92 KB
/
parse.hpp
File metadata and controls
82 lines (67 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*****************************************************************//**
* \file parse.hpp
* \brief contains a template function to parse
* comma-separated strings and store them in std::vector<T>.
*
* \author Xuhua Huang
* \date October 2021
*********************************************************************/
#ifndef PARSE_STR_HPP
#define PARSE_STR_HPP
#ifndef _IOSTREAM_
#include <iostream>
#endif
#ifndef _INC_STDLIB
#include <stdlib.h>
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _SSTREAM_
#include <sstream>
#endif
namespace util {
namespace parse {
template <char c>
constexpr bool is_digit = (c >= '0' && c <= '9');
/**
* Template to parse a delimiter-separated string.
* The default delimiter is a comma ','
* Ideal use case: convert such string to an integer array.
*/
template <typename T>
static const std::vector<T> parse_str(const std::string& str, char delimiter = ',') {
std::vector<T> result;
if (str.length() < 8E5) {
std::stringstream ss(str);
while (ss.good()) {
std::string substr;
getline(ss, substr, delimiter);
if constexpr (std::is_same_v<T, std::string>) {
result.push_back(substr);
} else if constexpr (std::is_same_v<T, char>) {
result.push_back(static_cast<char>(substr));
} else if constexpr (std::is_same_v<T, int>) {
result.push_back(stoi(substr));
}
}
}
return result;
}
/* Read digits from an integer and store in an array. */
static const std::vector<int> num_to_digits(int number) {
std::vector<int> digits;
if (number == 0) {
digits.push_back(0);
} else {
while (number != 0) {
int last = number % 10;
digits.insert(digits.begin(), 1, last);
number = (number - last) / 10;
}
}
return digits;
}
} // namespace parse
} // namespace util
#endif