-
Notifications
You must be signed in to change notification settings - Fork 0
/
Path.cpp
76 lines (65 loc) · 1.66 KB
/
Path.cpp
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
#include "Path.h"
#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
//
// Uses a map for quick add/remove/lookup and preserves the original order
// of the string by saving the position as the map value
//
Path::Path(const string& pathStr) {
setPath(pathStr);
}
//
// Split the path string on ';' and build our map
//
void Path::setPath(const string& pathStr) {
string buf = "";
char delim = ';';
position = 0;
for (char chr : pathStr) {
if (chr == delim) {
if (buf != "") {
add(buf);
}
buf = "";
} else {
buf += chr;
}
}
if (buf.length() > 0) {
add(buf);
}
}
bool Path::contains(const string& str) {
return pathMap.find(str) != pathMap.end();
}
void Path::remove(const string& str) {
pathMap.erase(str);
}
void Path::add(const string& str) {
pathMap[str] = position++;
}
//
// Rebuild the path string by sorting the values in the map based
// on the key (position) and imploding
//
string Path::get() {
vector<pair<string, int>> ordered;
for (auto keyval : pathMap) {
ordered.push_back(keyval);
}
auto sortByPosition = [](const pair<string, int>& lhs, const pair<string, int>& rhs) {
return lhs.second < rhs.second;
};
sort(ordered.begin(), ordered.end(), sortByPosition);
string imploded;
for (auto pair : ordered) {
imploded.append(pair.first).append(";");
}
return imploded;
}
map<string, int, CaseInsensitive> pathMap;
int position;