2016-04-26 107 views
1

假设我有一个如下定义的字符串向量。使用另一个向量遍历一个向量的特定元素

std::vector<std::string> names; 
names.push_back("Zero" ); 
names.push_back("One" ); 
names.push_back("Two" ); 
names.push_back("Three"); 
names.push_back("Four" ); 
names.push_back("Five" ); 
names.push_back("Six" ); 
names.push_back("Seven"); 
names.push_back("Eight"); 
names.push_back("Nine" ); 

而且,让我们说我有过哪些元素定义了环矢量:

std::vector<int> indices; 
indices.push_back(0); 
indices.push_back(5); 
indices.push_back(6); 

我如何可以遍历的矢量names根据矢量indices的元素,例如访问名称:"Zero","Five""Six"?我知道:

for(vector<string>::iterator it=names.begin() ; it < names.end(); it++) 

迭代所有要素或元素,我们可以找到一个模式,例如,所有其他元素等,但关于迭代有没有图案或难以找到的图案元素是如何?一个向量如何用于另一个向量的迭代?喜欢的东西:

for(vector<int>::iterator it=indices.begin() ; it < indices.end(); it++) 
{ 
    names.at(indices.at(it)) 
    ... 
} 

回答

1

你也可以使用一个std::for_each呼叫与拉姆达访问indicies(1版) 此外,您还可以使用范围为基础的循环与rvalues(第2版)

#include <vector> 
#include <algorithm> 

int main() 
{ 
    std::vector<std::string> names; 
    names.push_back("Zero"); 
    names.push_back("One"); 
    names.push_back("Two"); 
    names.push_back("Three"); 
    names.push_back("Four"); 
    names.push_back("Five"); 
    names.push_back("Six"); 
    names.push_back("Seven"); 
    names.push_back("Eight"); 
    names.push_back("Nine"); 

    std::vector<int> indices; 
    indices.push_back(0); 
    indices.push_back(5); 
    indices.push_back(6); 

    // version 1 
    std::for_each(std::cbegin(indices), std::cend(indices), 
    [&](auto &idx) { std::cout << names.at(idx) << "\n";}); 

    // version 2 
    for (auto &&idx : indices) 
    std::cout << names.at(idx) << "\n"; 

    return 0; 
} 
+0

显然,'汽车''C + 11'有问题。编译器抱怨C++ 11中的自动更改;请删除它。 – AFP

+0

这是'C++ 14'特有的。如果您使用的是“C++ 11”,则必须使用特定的类型替换“auto”。 – foo

2

它是如此简单:

for(vector<int>::iterator it=indices.begin() ; it != indices.end(); ++it) 
{ 
    names.at(*it); 
    names[*it]; // for faster but unvalidated access 
    ... 
} 

注:++it可能会更快(但不能慢一些),所以它通常用于当你不关心,如果它是后缀或前缀形式。 it != container.end()也是通常使用的,因为它更通用(比随机访问迭代器更少,但不适用于前向迭代器)。

3

你的建议几乎是正确的。而不是insdices.at(it),你应该取消引用迭代器。但是你可以这样做只是这样的:

for(int index : indices) { 
    names[index]; 
} 

或者你可以使用​​,如果你不能证明names.size()>indices[i]所有i

相关问题