Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Indexed Manager Snippets #125

Open
LuchoBazz opened this issue Aug 24, 2024 · 0 comments
Open

Add Indexed Manager Snippets #125

LuchoBazz opened this issue Aug 24, 2024 · 0 comments

Comments

@LuchoBazz
Copy link
Owner

#include <bits/stdc++.h>

using namespace std;

using Row = tuple<int, int, int>;
const int N_ELEM = 3;

const Row NONE = {-1, -1, -1};

class IndexedManager {
private:
  set<Row> tuples;
  map<int, Row> col_index[3];

public:
  void add(const Row &new_value) {
    if (tuples.insert(new_value).second) {
      col_index[0][get<0>(new_value)] = new_value;
      col_index[1][get<1>(new_value)] = new_value;
      col_index[2][get<2>(new_value)] = new_value;
    }
  }

  Row find(int column, int value) {
    assert(1 <= column && column <= N_ELEM);

    auto &index = col_index[column - 1];
    auto it = index.find(value);

    if (it != index.end()) {
      return it->second;
    }
    return NONE;
  }

  Row del(int column, int value) {
    assert(1 <= column && column <= N_ELEM);

    auto &index = col_index[column - 1];
    auto it = index.find(value);

    if (it != index.end()) {
      Row tupleToRemove = it->second;
      tuples.erase(tupleToRemove);

      col_index[0].erase(get<0>(tupleToRemove));
      col_index[1].erase(get<1>(tupleToRemove));
      col_index[2].erase(get<2>(tupleToRemove));

      return tupleToRemove;
    }
    return NONE;
  }
};

void print_im(const Row &tp) {
  cout << "(" << get<0>(tp) << ", " << get<1>(tp) << ", " << get<2>(tp) << ")"
       << '\n';
}

int main() {
  IndexedManager im;
  im.add(make_tuple(1, 20, 36));
  im.add(make_tuple(2, 2, 33));
  im.add(make_tuple(3, 32, 32));
  im.add(make_tuple(4, 222, 23));
  im.add(make_tuple(5, 23, 563));
  im.add(make_tuple(7, 232, 456));

  auto r1 = im.find(1, 1);
  print_im(r1);
  auto r2 = im.del(2, 20);
  print_im(r2);
  auto r3 = im.find(1, 1);
  print_im(r3);

  return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant