英文:
a function-definition is not allowed here before ‘:’ token
问题
在尝试编写下面的代码以迭代遍历unordered_map时,我遇到了以下错误。对该错误没有太多的理解。
错误信息:
在‘:’令牌之前不允许函数定义
英文:
While trying to write the below piece of code to iterate over an unordered_map I am struggling with the below error. Not getting much sense of that error.
#include <iostream>
#include <tr1/unordered_map>
using namespace std::tr1;
unsigned char *expr = (unsigned char *)bufin;
unordered_map <char, int> freq_map;
while(expr != '#include <iostream>
#include <tr1/unordered_map>
using namespace std::tr1;
unsigned char *expr = (unsigned char *)bufin;
unordered_map <char, int> freq_map;
while(expr != '\0')
{
char ch = *expr;
freq_map[ch]++;
expr++;
}
expr = (unsigned char *)bufin;
for(auto & it: freq_map)
{
std::cout<<it.first<<"\t"<<it.second);
}
')
{
char ch = *expr;
freq_map[ch]++;
expr++;
}
expr = (unsigned char *)bufin;
for(auto & it: freq_map)
{
std::cout<<it.first<<"\t"<<it.second);
}
The error:
a function-definition is not allowed here before ‘:’ token
答案1
得分: 1
如果您正在使用一个早于C++11的编译器,就不能使用范围-based for
循环,必须使用迭代器而不是。
// 辅助类型定义,以避免重复输入`unordered_map<char, int>`:
typedef unordered_map<char, int> maptype;
// 当您需要`char*`时,请不要将其强制转换为`unsigned char*`:
char* expr = (char*)bufin; // 如果`bufin`已经是`char*`,则根本不需要转换
maptype freq_map; // 使用辅助类型定义
while (*expr != '// 辅助类型定义,以避免重复输入`unordered_map<char, int>`:
typedef unordered_map<char, int> maptype;
// 当您需要`char*`时,请不要将其强制转换为`unsigned char*`:
char* expr = (char*)bufin; // 如果`bufin`已经是`char*`,则根本不需要转换
maptype freq_map; // 使用辅助类型定义
while (*expr != '\0') { // 解引用expr
char ch = *expr;
freq_map[ch]++;
expr++;
// 或者:++freq_map[*expr++];
}
// 使用迭代器的循环。再次使用辅助类型定义
for (maptype::iterator it = freq_map.begin(); it != freq_map.end(); ++it) {
std::cout << it->first << '\t' << it->second << '\n';
}
') { // 解引用expr
char ch = *expr;
freq_map[ch]++;
expr++;
// 或者:++freq_map[*expr++];
}
// 使用迭代器的循环。再次使用辅助类型定义
for (maptype::iterator it = freq_map.begin(); it != freq_map.end(); ++it) {
std::cout << it->first << '\t' << it->second << '\n';
}
英文:
If you are using a pre C++11 compiler, you can't use range-based for
loops and must instead use iterators.
// helper type definition to not have to repeat typing
// `unordered_map<char, int>` a lot:
typedef unordered_map<char, int> maptype;
// don't cast to `unsigned char*` when you need a `char*`:
char* expr = (char*)bufin; // if `bufin` is already a `char*`, don't cast at all
maptype freq_map; // using the helper type definition
while (*expr != '\0') { // dereference expr
char ch = *expr;
freq_map[ch]++;
expr++;
// or: ++freq_map[*expr++];
}
// Your loop, using an iterator instead. Again using the helper typedef
for (maptype::iterator it = freq_map.begin(); it != freq_map.end(); ++it) {
std::cout << it->first << '\t' << it->second << '\n';
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论