我必须将增加的 ID 作为 key 保存到 levelDB 数据库中。所以我得到的(以及我必须给 levelDB 的)是一个字符串。
问题:有没有一种优雅的方法来增加保存在字符串中的数字?
例子:
std::string key = "123";
[..fancy code snipped to increase key by 1..]
std::cout << key << std::endl; // yields 124
干杯!
PS:宁愿继续使用标准编译,即没有 C++11。
#include <sstream>
std::string key = "123";
std::istringstream in(key);
int int_key;
in >> int_key;
int_key++;
std::ostringstream out;
out << int_key;
key = out.str();
std::cout << key << std::endl;
您也可以使用 c 样式转换:
std::string key = "123";
int int_key = atoi(key.c_str());
int_key++;
char key_char[20];
itoa(int_key, key_char, 10);
key = key_char;
cout << key << endl;
您总是可以编写一个小例程来执行以 10 为底的算术运算,但最简单的解决方案通常是将数字保留为int(或其他整数类型),并根据需要将其转换为字符串。
也许是这样的:
std::string key = "123";
std::stringstream out;
out << (atoi(key.c_str()) + 1);
key = out.str();
代码:
istringstream iss(key);
int ikey;
iss >> ikey;
ostringstream oss;
oss << (ikey+1);
key = oss.str();
啊,leveldb确实接受字符串并且它可以返回一个字符串,但是该Slice结构也有一个带有不透明数据数组的构造函数:
// Create a slice that refers to data[0,n-1].
Slice(const char* data, size_t n)
当您获得密钥时Slice,您仍然拥有 achar*作为数据,因此您不必真正为字符串烦恼:
// Return a pointer to the beginning of the referenced data
const char* data() const { return data_; }
如果您的整个目标是将整数作为键,那么只需将整数转换为 char* 并将其存储在 中leveldb,如下所示:
int oldKey = 123;
char key[8];
memset(key, 0, 8);
*(int*)(&key) = oldKey;
*(int*)(&key) += 1;
// key is now 124
// want to put it back in a slice?
Slice s(key, sizeof(int));
不需要讨厌和昂贵的字符串...