如何以 if else 或切换大小写格式对自动和编码?
How to code the auto& in a if else or switch case format?
我曾经有一个代码来提取某些部分
auto& c = m_matrix[name];
....large block of code with using c in the calculation...
现在我必须使用 if/else 或切换大小写来m_matrix选项,如以下语句:
switch input{
case 1:
auto& c = A[name];
case 2:
auto& c = B[name];
}
....large block of code with using c in the calculation...
A 和 B 具有相同类型的元素。但是,这是错误的,因为它将显示c的定义是重复的。同时,我不能声明自动和c;在开关/机箱之前,如下所示:
auto& c;
switch input {
case 1:
c = A[name];
case 2:
c = B[name];
}
....large block of code with using c in the calculation...
有没有办法解决这个问题?
更新:CinCout - 恢复莫妮卡善意地提供了一个解决方案
switch input {
case 1:{
auto& c = A[name];
....large block of code with using c in the calculation...
}
case 2:{
auto& c = B[name];
....large block of code with using c in the calculation...
}
}
有没有办法避免每种情况下的重复代码?谢谢
只需为每个case
提供一个自己的作用域,有效地为每个c
提供一个局部作用域:
switch input
{
case 1:
{
auto& c = A[name];
…
break;
}
case 2:
{
auto& c = B[name];
…
break;
}
}
您可以使用函数或 lambda:
auto get_c = [&] -> decltype(A[name])& {
switch (input) {
case 1:
return A[name];
case 2:
return B[name];
}
return A[name]; // default case
};
auto& c = getC();
....large block of code with using c in the calculation...
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- 如何在openssl-ecc中获取十六进制格式的私钥
- 将"打开的CV图像"中的"颜色"转换为整数格式
- TDateTime格式在C++Builder中不会更改
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 检查不带转换的扫描格式
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- 是否可以从格式字符串中检索"width"
- clang格式:宏的缩进
- *新的编码器*格式和运算符
- 如何以 if else 或切换大小写格式对自动和编码?
- 为什么我在有关文件编码格式的QT代码中获得了混乱的代码
- 如何在C++中将文件编码格式设置为UTF8
- UTF 8 以 XML 格式编码的日语字符串
- LZW 编码和 GIF 文件格式
- 如果可以用IEEE 754中的二进制格式表示,那么硬编码浮点精确吗
- 获取url参数值以某种格式编码
- 我怎么能得到QT主函数argv参数作为unicode编码格式
- OpenCV imencode pgm 不能编码正确的格式