简体   繁体   English

字符串数组的C ++动态向量

[英]C++ dynamic vector of string array

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. 我将值正确插入到res变量中,但是我的代码无法正常工作:打印循环执行了4次,但每次仅打印LAST元素。 I believe the problem could be: 1) I don't push the strings array properly in the vector; 我认为问题可能是:1)我没有正确地将字符串数组推入向量; 2) I don't manage correctly the iteration over the vector and over all the string when I want to print it. 2)当我想打印向量和所有字符串时,我不能正确地管理迭代。

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;
};

std::string res[columns.size() + 1]; is a variable length array and you are pushing a pointer to the first element into the vector. 是一个可变长度的数组,您正在将指向第一个元素的指针推入向量中。 You should use std::vector<std::string> res; 您应该使用std::vector<std::string> res; and std::vector<std::vector<std::string>> results; std::vector<std::vector<std::string>> results;

std::vector<std::vector<std::string>> DatabaseConnector::ExecuteQuery(std::string query, const std::vector <std::string> &columns)
{
    std::vector<std::vector<std::string>> results;

    db_params.res = db_params.stmt->executeQuery(query);
    while (db_params.res->next()) // Access column data by alias or column name
    {
        std::vector<std::string> res;
        for(std::string s : columns)
            res.push_back(db_params.res->getString(s));

        results.push_back(res);
    }

    for(const auto &el :results)
    {
        for (const auto &res : el)
             std::cout << res << " ";

        std::cout << std::endl;
    }

    return results;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM