I want to create a dynamic vector and each vector element is an array of strings.
The data structure I have in mind is something like this:
VECTOR:
[0] = [str1, str2, str3]
[1] = [str1, str2, str3]
[2] = [str1, str2, str3]
I correctly insert the values in the res variable BUT my code doesn't work properly: the printing loop is executed 4 times but every time it prints only the LAST element. I believe the problem could be: 1) I don't push the strings array properly in the vector; 2) I don't manage correctly the iteration over the vector and over all the string when I want to print it.
This is my code:
std::vector<std::string*> DatabaseConnector::ExecuteQuery(std::string query, std::vector <std::string> columns)
{
std::vector<std::string*> results;
std::string res[columns.size() + 1]; // last value = '\0' to signal end of array
db_params.res = db_params.stmt->executeQuery(query);
while (db_params.res->next()) // Access column data by alias or column name
{
int i = 0;
for(std::string s : columns)
res[i++] = db_params.res->getString(s);
res[i] = "\0";
results.push_back(res);
}
for(auto el :results)
{
int i=0;
while(el[i].compare("") != 0)
std::cout << el[i++] << " ";
std::cout << std::endl;
}
return results;
};
vector<vector<string>>(also:std::string res[columns.size() + 1];is not portable code because VLAs are not standardized, they're an extension of your compiler)std::vector<std::vector<whatever>>. The whole purpose of vector is that it can be dynamic, and nothing stops you from having a vector of vectors.