2012-01-27 59 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

也许最简单的方法是将您的向量数组(或矢量的矢量如果在它们的变量数)。

我想你还想要一个“矢量名称”数组来满足你的第二个条件。