如何使用另一个变量声明一个变量
How to declare a variable using another variable?
我正在尝试在C++中创建一个函数,该函数可以根据提供的名称创建一个新的整数类型变量
例如
void my_variable(char name)
{
int "something here" = 1; // i am figuring out what to write
// there so that it makes a variable from that character that i have sent
cout << "something here";
}
看看使用 std::map
.它允许您创建键值对。在此实例中,键将name
,值将为 int。以下代码片段演示了如何创建地图,填充地图,然后基于键搜索值。
void my_function(std::string name)
{
std::map<std::string, int> myMap;
myMap[name] = 1; //
cout << "Key " << name << " holds " << paramMap.find(name)->second << std::endl;
}
由于没有人将其作为答案发布,因此有时定义宏来创建变量很方便。
#define DEFINE_HELPER(x) Helper helper_##x = Helper(#x)
#define HELPER(x) (&helper_##x)
struct Helper {
std::string name;
Helper (const char *s) : name(s) {}
};
DEFINE_HELPER(A);
DEFINE_HELPER(B);
std::cout << HELPER(A)->name << std::endl;
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 用C++中的一个变量定义一个常量
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 全局变量 多读取器 一个写入器多线程安全?
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 一个变量的输入值也会保存到另一个变量中
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 在另一个函数 (c++) 中调用变量
- 将双精度变量设置为另一个变量的值
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 如果我注释掉换行符,为什么'string'会成为一个不合格的变量
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- C++使用cin给变量一个非整数的值
- 怎么可能有两个同名的变量——一个是全局变量,另一个是局部变量