2015-05-01 34 views
1

我有2個字符串,來自Sqlite3,ColName和Value。我想保存每一對值,我不知道ColName/Value的數量,所以我使用矢量。如何在C++中創建一個數組(字符串[])的向量

是有辦法,所以我可以創建/推COLNAME /值對的陣列

代碼的矢量:

std::vector<std::string[3]> colNameAndValueList;//this doesnt work 
string colName="ID"; 
string value="122001"; 
colNameAndValueList.push_back(std::string(colName,value));//im lost here 

我不知道是否我應該使用散列或結構,任何人都可以給我一個建議?

感謝。

+2

您可以使用'的std :: pair'在'std :: vector >'。 – huu

+0

非常感謝!這將做的工作! :D @huu –

回答

2

有很多方法來剝皮這隻貓。您可以使用std::pairemplace_back構建pair到位,當你插入值到您的數組:

std::vector<std::pair<std::string, std::string>> records; 

std::string column = "hello"; 
std::string value = "world"; 

records.emplace_back(column, value); // Use existing strings 
records.emplace_back("new", "value"); // Use c-string literals 

for (auto& record : records) { 
    std::cout << record.first << ": " << record.second << std::endl; 
} 

/* 
* Prints: 
* hello: world 
* new: value 
*/ 

這裏有一個working example

+0

非常感謝! ,auto&會和'std :: vector > :: iterator it = records.begin(); it!= records.end(); it ++)'? –

+0

實際上它是相同的,因爲它們都可以讓你遍歷矢量。在代碼中,'auto&record'是位於向量中的實際的'std :: pair >'對象。 – huu

+0

這隻適用於C++ 11嗎? –

3

我建議你使用結構的std::vector

struct Name_Value 
{ 
    std::string name; 
    std::string value; 
}; 

typedef std::vector<Name_Value> Name_Value_Container; 

這是一個更容易閱讀,理解和實施。

2

您可以使用std::pair類型的對象的向量。例如

std::vector<std::pair<std::string, std::string>> colNameAndValueList; 

std::array類型的對象的矢量。例如

std::vector<std::array<std::string, 2>> colNameAndValueList; 

普通數組沒有複製賦值運算符。所以最好不要在標準容器中使用它們。

這裏是一個示範項目

#include <iostream> 
#include <vector> 
#include <array> 


int main() 
{ 
{ 
    std::vector<std::pair<std::string, std::string>> colNameAndValueList; 

    colNameAndValueList.push_back({ "ID", "122001" }); 

    for (const auto &p : colNameAndValueList) 
    { 
     std::cout << p.first << ' ' << p.second << std::endl; 
    } 

} 
{ 
    std::vector<std::array<std::string, 2>> colNameAndValueList; 

    colNameAndValueList.push_back({ "ID", "122001" }); 

    for (const auto &a : colNameAndValueList) 
    { 
     for (const auto &s : a) std::cout << s << ' '; 
     std::cout << std::endl; 
    } 

} 

    return 0; 
} 

程序輸出是

ID 122001 
ID 122001 
0

要放在一個答案,@huu已是正確的,使用

std::vector<std::pair<std::string, std::string>> myVector 

    std::pair("ID", "122001") mypair; 
    myVector.push_back(mypair); 

還是一個用戶定義的結構。

// In your .h file 
    struct myPair { 
     std::string one; 
     std::string two; 
    }; 
// in your .c file 
     myPair res; 
     res.one = "ID"; 
     res.two = "122001"; 
     std::vector<myPair> myVector; 
     myVector.push_back(res); 
0

試試這個:

vector<pair<string, string>> colNameAndValueList; 
    string colName = "ID"; 
    string value = "122001"; 
    colNameAndValueList.push_back({ colName, value }); 

如果您需要在您的記錄超過兩個字符串,那麼你可以使用:

vector<vector<string>> colNameAndValueList; 
相關問題