2

増加する ID をキーとして levelDB データベースに保存する必要があります。したがって、得られるもの (および levelDB に渡さなければならないもの) は文字列です。

質問: 文字列に保存された数値を増やすエレガントな方法はありますか?

例:

std::string key = "123";
[..fancy code snipped to increase key by 1..]
std::cout << key << std::endl;  // yields 124

乾杯!

PS: 標準のコンパイル、つまり C++11 を使用しないことを希望します。

4

5 に答える 5

3
#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;
于 2012-02-16T10:34:28.910 に答える
2

基数10の算術演算を行う小さなルーチンをいつでも作成できますが、最も簡単な解決策は、通常、数値をint(または他の整数型)として保持し、必要に応じてそれを文字列に変換することです。

于 2012-02-16T10:34:01.493 に答える
1

おそらくこのようなもの:

std::string key = "123";
std::stringstream out;
out << (atoi(key.c_str()) + 1);
key = out.str();
于 2012-02-16T10:32:55.563 に答える
0

コード:

istringstream iss(key);
int ikey;
iss >> ikey;
ostringstream oss;
oss << (ikey+1);
key = oss.str();
于 2012-02-16T10:33:48.427 に答える
0

ああ、確かに leveldb は文字列を取り込んで文字列を返すことができますSlice構造体には不透明なデータ配列を持つコンストラクタもあります。

// Create a slice that refers to data[0,n-1].
Slice(const char* data, size_t n)

キーを取得しても、データとしてSliceまだあるchar*ので、文字列を気にする必要はありません。

// 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));

面倒で高価な弦は必要ありません...

于 2012-02-16T11:09:10.300 に答える