2012-01-27 43 views
1

我無法搜索潛在的重複項,因爲我不確定正確的術語是什麼。通過幾個向量循環

如果我有很多已經創建的向量,我怎麼能通過它們循環?爲了簡單起見,假設我有三個向量名爲"vec_one""vec_two","vec_three"的字符串向量。

我想要做的事,如:

for i in ("vec_one", "vec_two", "vec_three") { 
    for (vector<string>::const_iterator iter = i.begin(); iter != i.end(); ++iter) { 
     //do something with the elements ***and I need to access "i"***, that is, the vector name. 
    } 
} 

這將是一樣的寫循環三種不同的,但會更容易閱讀,其實我有三個以上的在我的非簡單的應用程序。

請注意,因爲我需要訪問矢量名稱(請參閱評論),所以我不能將它們全部合併在一起,然後運行一個循環。

+0

製作一個指向vec_o​​ne,vec_two等的指針數組......外部循環遍歷這些指針的數組,通過外部循環索引訪問內部循環。 – lapk 2012-01-27 01:34:38

+0

@AzzA你不能做一個引用數組 – 2012-01-27 01:36:41

+0

@SethCarnegie你是對的,我的壞。 – lapk 2012-01-27 01:52:20

回答

1

你可以把向量在vector<std::pair<std::string, std::vector<...>*>

std::vector<std::pair<std::string, std::vector<std::string>*> > vectors; 
vectors.emplace_back(std::string("vec_one"), &vec_one); //or push_back(std::make_pair(...)) in C++03 
vectors.emplace_back(std::string("vec_two"), &vec_two); 
vectors.emplace_back(std::string("vec_three"), &vec_three); 
for(auto iter = vectors.begin(); iter != vectors.end(); ++iter)//used c++11 auto here for brevity, but that isn't necessary if C++11 is not availible 
    for(auto vecIter = iter->second->begin(); vecIter != iter->second->end(); ++vecIter) 
    //get name with iter->first, body here 

這樣,你可以從外部迭代器輕鬆獲得名。

如果使用C++ 11可以使用std::array代替:

std::array<std::pair<std::string, std::vector<std::string>*>, 3> vectors = 
{ 
    std::make_pair(std::string("vec_one"), &vec_one), 
    std::make_pair(std::string("vec_two"), &vec_two), 
    std::make_pair(std::string("vec_three"), &vec_three) 
}; 

在C++ 03可以使用的buildin數組,但除非該vector的額外開銷是你的問題(不太可能)我沒有看到一個令人信服的理由這樣做。 boost::array也是一個值得關注的選擇,如果您不能使用C++ 11

如果你需要絕對的最佳性能,這可能是歡顏直接使用const char*,而不是std::string的名字。

+0

謝謝你,灰熊。我特別欣賞你允許的不同選項。不幸的是,我必須使用C++ 03。 – 2012-01-27 01:50:48

+0

誰低估了這個答案:downvote的解釋會很好,因爲我沒有看到這個答案有什麼問題。 – Grizzly 2012-01-27 02:04:51

6

你可以用一個數組做到這一點:

const vector<string>* varr[] = { &vec_one, &vec_two, &vec_three, &etc }; 

for (auto vec = begin(varr); vec < end(varr); ++vec) 
    for (vector<string>::const_iterator iter = begin(**vec); iter != end(**vec); ++iter) 
     //do something with the elements 
+0

謝謝Seth。這似乎是最自然的做法。 – 2012-01-27 01:50:09

0

也許最簡單的方法是將您的向量數組(或矢量的矢量如果在它們的變量數)。

我想你還想要一個「矢量名稱」數組來滿足你的第二個條件。