管理字符串文本的最佳做法
Best practice to manage string literals
在一个文件中管理字符串而不是多次写出字符串的最佳实践是什么?我的想法是创建一个简单的 string_library.h 文件,该文件包含映射中的所有字符串,并方便地定义以获取名称和 ID。像这样:
#include <string>
#include <map>
#define SENSOR1_ID 0
#define SENSOR2_ID 1
#define SENSOR1_NAME string_library[SENSOR1_ID]
#define SENSOR2_NAME string_library[SENSOR2_ID]
std::map<unsigned int, const std::string> string_library{
std::make_pair(SENSOR1_ID, "Sensor1 Name"),
std::make_pair(SENSOR2_ID, "Sensor2 HI Name")
};
这样,字符串只需写出一次,并且可以通过定义或从映射中轻松抓取。地图对于能够迭代地图可能很有用,但也许其他一些结构更有意义。
您可以简单地使用constexpr
变量:
constexpr auto SENSOR1_NAME = "Sensor1 Name";
不需要宏,也不需要昂贵的动态内存开销。
相关文章:
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 管理字符串文本的最佳做法
- 连接和压缩标准::vector<std::字符串的最佳方法>
- 将位字符串转储到二进制文件的最佳方法是什么
- 在C++中拆分字符串的最佳做法
- 当通过常量和不是字符串的最佳选择时,是否有任何情况?
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法
- 当字符串中只有一个"GOOD"字符串可用时,从没有空格的字符串中提取第一个单词的最佳和有效方法?
- C++ std::string 中是否有任何函数可以计算两个字符串的相同起始字符的总数或任何最佳方法
- 总结数字字符串输入的最佳方法
- 在字符串中找到单词出现数量的最佳方法(C ,字符串中没有空格)
- 连接字符串的最佳方法是什么?
- 消除从字符串常量到'char*'的已弃用转换的最佳方法"
- 将字符串中的特定单词与c 中的if或while进行比较的最佳方法
- 根据特定数据对字符串进行排序的最佳方法是什么
- 在C 中将字符串归为字符串的最佳方法是什么?
- 将映射从字符串到INT的最佳方法,而另一个同时进行的方式
- 在C++中分隔字符串并存储到数组中的最佳方法
- 适用于短文件名的最佳字符串哈希函数
- 此示例的最佳字符串哈希函数