Skip to content

Instantly share code, notes, and snippets.

@htfy96
Created January 8, 2017 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save htfy96/3a5ef5ba544ae0beb3ca7bc38425e325 to your computer and use it in GitHub Desktop.
Save htfy96/3a5ef5ba544ae0beb3ca7bc38425e325 to your computer and use it in GitHub Desktop.
A use case of user defined literals in C++
#include <iostream>
#include <vector>
#include <utility>
#include <initializer_list>
#include <iterator>
#include <cassert>
#include <climits>
#include <map>
using namespace std;
enum class Player { B, W };
struct Piece
{
unsigned long long seq;
Player player;
};
Piece operator""_W(unsigned long long seq)
{
return Piece { seq, Player::W };
}
Piece operator""_B(unsigned long long seq)
{
return Piece { seq, Player::B };
}
constexpr unsigned long long INVALID_SEQ = ULLONG_MAX;
constexpr Piece O {INVALID_SEQ, Player::B};
constexpr bool isValidPiece(Piece p)
{
return p.seq != INVALID_SEQ;
}
struct PieceToPlace
{
Player player;
pair<int, int> point;
PieceToPlace(Player p, int x, int y):
player(p), point(x, y)
{}
bool operator ==(const PieceToPlace &other) const
{
return player == other.player &&
point == other.point;
}
};
auto getInput(const initializer_list< initializer_list<Piece> > &il)
-> vector<PieceToPlace>
{
int row = distance(il.begin(), il.end());
int col = -1;
for (auto &row : il)
{
int cur_col = distance(row.begin(), row.end());
if (col > 0)
assert(col == cur_col && "Not a rectangle");
col = cur_col;
}
map<int, PieceToPlace> result_map;
for (int i = 0; i<row; ++i)
{
auto &cur_row = il.begin()[i];
for (int j = 0; j<col; ++j)
{
auto &element = cur_row.begin()[j];
if (isValidPiece(element))
result_map.emplace(piecewise_construct,
forward_as_tuple(element.seq),
forward_as_tuple(element.player, i, j)
);
}
}
vector<PieceToPlace> ans;
ans.reserve(result_map.size());
for (auto &piece_to_place_pair : result_map)
ans.push_back(piece_to_place_pair.second);
return ans;
}
int main()
{
auto placeVec = getInput({
{O, 1_B, 2_W, 4_W},
{6_W, 3_B, 5_B, 7_W},
{O, O, O, 8_B},
{9_W, O, O, O}
});
assert(placeVec.size() == 9);
for (auto &ele : placeVec)
{
cout << (ele.player == Player::B ? "B" : "W") << " " << ele.point.first << "," << ele.point.second << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment