I'm trying to solve an interval problem using double pointers. The basic premise is to store double pointers to an Interval struct in my map so I can update the interval without needing to iterate over any other values in my map. Using double pointers seems to be causing some unexpected changes to my intervals, and I don't understand why.
Here's my current code:
#include <iostream>
#include <vector>
#include <utility>
#include <unordered_map>
using namespace std;
int main()
{
vector<pair<int, char>> sequence = {
{0,'a'},
{1,'-'},
{2,'b'},
{3,'c'},
{4,'-'},
{5,'d'},
{6,'e'},
{7,'-'},
{8,'f'},
{10,'g'},
{11,'-'},
{12, '-'}
};
struct Interval {
string word;
bool startH;
bool endH;
Interval(string word) : word(word), startH(false), endH(false) {}
};
Interval* hyphen = new Interval("-");
Interval** hPtr = ‐
auto consolidate = [&hPtr](Interval**& left, Interval**& right) {
//cout << "\t(" << (*left)->word << " " << (*right)->word << ")" << endl;
if (left == hPtr && right == hPtr) return;
if (left == hPtr) {
(*right)->startH = true;
}
else if (right == hPtr) {
(*left)->endH = true;
}
else {
(*right)->startH = (*left)->startH;
(*right)->word = (*left)->word + (*right)->word;
(*left) = (*right);
}
if ((*right)->startH && (*right)->endH) {
cout << "RESULT: " << (*right)->word << endl;
}
else if ((*left)->startH && (*left)->endH) {
cout << "RESULT: " << (*left)->word << endl;
}
};
unordered_map<int, Interval**> intervals;
for (auto pair : sequence) {
int index = pair.first;
char c = pair.second;
cout << "----" << index << ", " << c << "-----" << endl;
int preIndex = index - 1;
int postIndex = index + 1;
auto it_pre = intervals.find(preIndex);
auto it_post = intervals.find(postIndex);
//HERE 1
//if (it_pre != intervals.end()) cout << (*(it_pre->second))->word << endl;
Interval** currentIntervalPtr;
if (c == '-') {
currentIntervalPtr = hPtr;
}
else {
Interval* currentInterval = new Interval(string(1, c));
currentIntervalPtr = ¤tInterval;
}
//HERE 2
//if (it_pre != intervals.end()) cout << (*(it_pre->second))->word << endl;
if (it_pre != intervals.end()) {
Interval** prePtr = it_pre->second;
//cout << "PRE: <" << (*currentIntervalPtr)->word << ", " << (*prePtr)->word << ">>" << endl;
consolidate(prePtr, currentIntervalPtr);
}
if (it_post != intervals.end()) {
Interval** postPtr = it_post->second;
//cout << "POST: <" << (*currentIntervalPtr)->word << ", " << (*postPtr)->word << ">>" << endl;
consolidate(currentIntervalPtr, postPtr);
}
intervals[index] = currentIntervalPtr;
}
return 0;
}
Between my two print statements (HERE 1 and HERE 2), the value of (*(it_pre->second))->word changes. All I've done between these statements is create a new, unrelated Interval, so I don't understand why my map values are changing.
Any insights would be appreciated. I'm new to using double pointers, so I might just be overlooking something simple.