[英]How to retrieve an enum index value based on char array? in C++ (cpp)
Disclaimer: New to programming, learning on the fly.免责声明:编程新手,即时学习。 This is my first post and apologize if the question is not written clearly.
这是我的第一篇文章,如果问题没有写清楚,我深表歉意。
I am trying to go through a tutorial on building a chess engine, but it is written in C and I am attempting to convert it to C++ code.我正在尝试通过有关构建国际象棋引擎的教程来 go,但它是用 C 编写的,我正在尝试将其转换为 C++ 代码。 The idea of the code is to enter a char and retrieve the index value of an enum.
代码的想法是输入一个字符并检索枚举的索引值。 I am getting a compile error because of this code.
由于此代码,我收到编译错误。 How do I approach this as it isn't clear to me after trying different ideas.
我该如何解决这个问题,因为在尝试不同的想法后我不清楚。
Eg std::cout << CHAR_TO_PIECE['k'];
例如
std::cout << CHAR_TO_PIECE['k'];
with expected output of 11.预期 output 为 11。
in "typedefs.h"
在
"typedefs.h"
中
enum Piece {P, N, B, R, Q, K, p, n, b, r, q, k};
in "board.h"
在
"board.h"
中
extern const int CHAR_TO_PIECE[];
and in board.c
并在
board.c
// convert ASCII character pieces to encoded constants
int CHAR_TO_PIECE[] = {
['P'] = P,
['N'] = N,
['B'] = B,
['R'] = R,
['Q'] = Q,
['K'] = K,
['p'] = p,
['n'] = n,
['b'] = b,
['r'] = r,
['q'] = q,
['k'] = k
};
A more C++ way to handle this is to use a std::map
(or std::unordered_map
), eg:处理此问题的更多 C++ 方法是使用
std::map
(或std::unordered_map
),例如:
#include <map>
enum Piece {P, N, B, R, Q, K, p, n, b, r, q, k};
extern const std::map<char, Piece> CHAR_TO_PIECE;
// convert ASCII character pieces to encoded constants
const std::map<char, Piece> CHAR_TO_PIECE = {
{'P', P},
{'N', N},
{'B', B},
{'R', R},
{'Q', Q},
{'K', K},
{'p', p},
{'n', n},
{'b', b},
{'r', r},
{'q', q},
{'k', k}
};
std::cout << (int) CHAR_TO_PIECE['k'];
You can write a function to return specific enum for you char input.您可以编写一个 function 来为您的字符输入返回特定的枚举。
enum Piece {P, N, B, R, Q, K, p, n, b, r, q, k};
Piece charToPiece(char ch)
{
switch (ch) {
case 'P':
return P;
case 'N':
return N;
case 'B':
return B;
case 'R':
return R;
case 'Q':
return Q;
case 'K':
return K;
case 'p':
return p;
case 'n':
return n;
case 'b':
return b;
case 'r':
return r;
case 'q':
return q;
case 'k':
return k;
}
}
You can create an array of enums with 2 x 26 entries (upper and lowercase), and assign every relevant entry the correct enum.您可以创建一个包含 2 x 26 个条目(大写和小写)的枚举数组,并为每个相关条目分配正确的枚举。 This must be coded manually.
这必须手动编码。 With such a correspondence table, character lookup is immediate.
有了这样的对应表,字符查找是立即的。 (You can also reserve a "unassigned" value if needed.)
(如果需要,您还可以保留“未分配”值。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.