[英]push_back on 2D std::vector< std::vector<char*> > value made all the values are the same
How can I adding the value in 2D vector std::vector< std::vector<char*> >如何在二维向量中添加值 std::vector< std::vector<char*> >
I was using this code, but the items result inside the vetore are the same.我正在使用此代码,但 vetore 中的项目结果是相同的。 Whereas the data from the db querying are varied.
而来自数据库查询的数据是多种多样的。
std::vector< std::vector<char*> > results;
char *dataTemp = new char[128];
sqlite3_stmt *statement;
int rc = sqlite3_prepare_v2(m_pDbFile, sql, -1, &statement, 0);
if( rc == SQLITE_OK )
{
int cols = sqlite3_column_count(statement);
int result = 0;
int count = 0;
while(true)
{
result = sqlite3_step(statement);
if(result == SQLITE_ROW)
{
std::vector<char*, std::allocator<char*>> values;
for(int col = 0; col < cols; col++)
{
char* value = (char*)sqlite3_column_text(statement, col);
values.push_back((char*)sqlite3_column_text(statement, col));
}
results.push_back(values);
}
else
{
break;
}
count++;
}
sqlite3_finalize(statement);
}
Problem问题
Pointer (C type string) returned by sqlite3_column_text
may be invalidated / reused after subsequent calls to sql APIs. sqlite3_column_text
返回的指针(C 类型字符串)在后续调用 sql API 后可能会失效/重用。 So you should preserve the contents instead of saving the pointer itself.所以你应该保留内容而不是保存指针本身。
Solution解决方案
Make the following 3 changes in your code.在您的代码中进行以下 3 处更改。
#include <string> // 1
...
std::vector< std::vector<std::string> > results; // 2
...
std::vector<std::string> values; // 3
for(int col = 0; col < cols; col++)
{
const char* value = (char*)sqlite3_column_text(statement, col); // Optional
values.push_back(value); // Optional
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.