[英]loop through several vectors
我在搜索潛在的重復項時遇到了麻煩,因為我不確定正確的術語是什么。
如果我已經創建了許多矢量,如何遍歷它們? 為簡單"vec_one"
,假設我有三個向量字符串,分別為"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.
}
}
這將與編寫三個不同的for循環相同,但會更具可讀性,實際上,我的非簡單應用程序中有三個以上。
請注意,因為我需要訪問向量名稱(請參見注釋),所以不能將它們全部合並在一起然后運行一個循環。
您可以使用數組來做到這一點:
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
您可以將向量放在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中,您可以改用內建數組,但是除非vector
的額外開銷對您來說是個問題(不太可能),否則我沒有令人信服的理由。 如果不能使用C ++ 11, boost::array
也是一個值得注意的選擇
如果確實需要絕對最佳的性能,那么直接使用const char*
而不是std::string
作為名稱可能是值得的。
可能最簡單的方法是將向量放在一個數組中(如果向量數量可變,則向量也可以)。
我猜您也希望一個“向量名稱”數組滿足您的第二個條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.