How can I adding the value in 2D vector std::vector< std::vector<char*> >
I was using this code, but the items result inside the vetore are the same. 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. So you should preserve the contents instead of saving the pointer itself.
Solution
Make the following 3 changes in your code.
#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
}
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.