gpt4 book ai didi

c++ - C++ 中的简明列表/vector

转载 作者:太空狗 更新时间:2023-10-29 20:31:16 26 4
gpt4 key购买 nike

我目前正在将 Python 中的算法转换为 C++。

这一行 EXCH_SYMBOL_SETS = [["i", "1", "l"], ["s", "5"], ["b", "8"], ["m", "n"]]现在是

    vector<vector<char>> exch_symbols;

vector<char> vector_1il;
vector_1il.push_back('1');
vector_1il.push_back('i');
vector_1il.push_back('l');

vector<char> vector_5s;
vector_5s.push_back('5');
vector_5s.push_back('s');

vector<char> vector_8b;
vector_8b.push_back('8');
vector_8b.push_back('b');

vector<char> vector_mn;
vector_mn.push_back('m');
vector_mn.push_back('n');

exch_symbols.push_back(vector_1il);
exch_symbols.push_back(vector_5s);
exch_symbols.push_back(vector_8b);
exch_symbols.push_back(vector_mn);

我讨厌为二维 vector 中的每个内部变量设置一个中间命名变量。我不太熟悉 C++ 中的多维数据结构。有没有更好的办法?

之后发生的事情是这样的:

multimap<char, char> exch_symbol_map;

/*# Insert all possibilities
for symbol_set in EXCH_SYMBOL_SETS:
for symbol in symbol_set:
for symbol2 in symbol_set:
if symbol != symbol2:
exch_symbol_map[symbol].add(symbol2)*/
void insert_all_exch_pairs(const vector<vector<char>>& exch_symbols) {
for (vector<vector<char>>::const_iterator symsets_it = exch_symbols.begin();
symsets_it != exch_symbols.end(); ++symsets_it) {
for (vector<char>::const_iterator sym1_it = symsets_it->begin();
sym1_it != symsets_it->end(); ++sym1_it) {
for (vector<char>::const_iterator sym2_it = symsets_it->begin();
sym2_it != symsets_it->end(); ++sym2_it) {
if (sym1_it != sym2_it) {
exch_symbol_map.insert(pair<char, char>(*sym1_it, *sym2_it));
}
}
}
}
}

所以这个算法应该以一种或另一种方式与这里的表示一起工作。目标是以后可以轻松更改 EXCH_SYMBOL_SETS 以包含新的 char 组或向现有组添加新字母。谢谢!

最佳答案

我会重构,而不是 vector<char> , 使用 std::string作为内部,即

vector<string> exch_symbols;
exch_symbols.push_back("1il");
exch_symbols.push_back("s5");
exch_symbols.push_back("b8");
exch_symbols.push_back("mn");

然后改变你的插入方法:

void insert_all_exch_pairs(const vector<string>& exch_symbols) 
{
for (vector<string>::const_iterator symsets_it = exch_symbols.begin(); symsets_it != exch_symbols.end(); ++symsets_it)
{
for (string::const_iterator sym1_it = symsets_it->begin(); sym1_it != symsets_it->end(); ++sym1_it)
{
for (string::const_iterator sym2_it = symsets_it->begin(); sym2_it != symsets_it->end(); ++sym2_it)
{
if (sym1_it != sym2_it)
exch_symbol_map.insert(pair<char, char>(*sym1_it, *sym2_it));
}
}
}
}

关于c++ - C++ 中的简明列表/vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4603331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com