簡體   English   中英

字符串數組的C ++動態向量

[英]C++ dynamic vector of string array

我想創建一個動態矢量,每個矢量元素都是一個字符串數組。

我想到的數據結構是這樣的:

VECTOR: 
[0] = [str1, str2, str3]
[1] = [str1, str2, str3]
[2] = [str1, str2, str3]

我將值正確插入到res變量中,但是我的代碼無法正常工作:打印循環執行了4次,但每次僅打印LAST元素。 我認為問題可能是:1)我沒有正確地將字符串數組推入向量; 2)當我想打印向量和所有字符串時,我不能正確地管理迭代。

這是我的代碼:

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]; 是一個可變長度的數組,您正在將指向第一個元素的指針推入向量中。 您應該使用std::vector<std::string> res; 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