Skip to content

Instantly share code, notes, and snippets.

@phoebe-leong
Last active October 24, 2021 02:58
Show Gist options
  • Save phoebe-leong/c25972c4bdac45d14b0c13b00f576530 to your computer and use it in GitHub Desktop.
Save phoebe-leong/c25972c4bdac45d14b0c13b00f576530 to your computer and use it in GitHub Desktop.
C++17 map
#pragma once
#include <string>
#include <vector>
template<typename T1, typename T2>
class map
{
private:
size_t map_size;
std::vector<T1> left;
std::vector<T2> right;
public:
void insert(T1 left_val, T2 right_val)
{
left.push_back(left_val);
right.push_back(right_val);
map_size++;
}
void insert(T1 left_val, T2 right_val, const int pos)
{
if (pos < left.size() && pos >= 0)
{
left.push_back(left[left.size() - 1]);
right.push_back(right[right.size() - 1]);
for (int i = left.size() - 2; i != pos; i--)
{
left[i] = left[i - 1];
right[i] = right[i - 1];
}
left[pos] = left_val;
right[pos] = right_val;
} else
{
insert(left_val, right_val);
}
map_size++;
}
void remove(const int pos)
{
for (int i = pos; i < left.size(); i++)
{
left[i] = left[i + 1];
right[i] = right[i + 1];
}
map_size--;
}
std::string iterate(const char divider = ':')
{
static int iterator = 0;
std::string ret;
if (left[iterator] != "\0")
{
iterator++;
std::string res;
if constexpr(std::is_convertible<T1, int>::value)
{
res = std::to_string(left[iterator - 1]);
} else
{
res.append(left[iterator - 1]);
}
res.append(" ");
res.append(std::to_string(divider));
res.append(" ");
if constexpr(std::is_convertible<T2, int>::value)
{
res.append(std::to_string(right[iterator - 1]));
} else
{
res.append(right[iterator - 1]);
}
return res;
}
return "";
}
size_t size() { return map_size; }
map()
{
map_size = 0;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment