2016-04-26 67 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

相關問題