2016-03-13 71 views
-2

我有這個問題我目前正在C++中工作。使用列表作爲索引從另一個列表中打印某些元素

給出一個清單L和另一個清單P,其中包含按照升序 排序的整數。操作printLots(L,P)將打印位於由P指定的位置 中的L中的元素。例如,如果P = 1,3,4,6,位置1,3,4和6中的元素爲 在L中被打印。寫入程序printLots(L,P)。您只能使用公開的 STL容器操作。

這是我到目前爲止的代碼。

void printLots(list<int> L, list<int> P) 
{ 
    list<int>::iterator myListIterator; 

    for (myListIterator = P.begin(); 
     myListIterator != P.end(); 
     ++myListIterator) 
    { 
     //Not sure what to do here 
    } 
} 

我知道我可以很容易地打印列表P的內容,但我不知道如何使用它作爲索引打印根據我的研究在列表L的位置元素,沒有直接索引列表的方式,所以我不太確定從這裏去哪裏。

+0

使用計數器... –

+0

@KarolyHorvath對不起,我不知道這將有助於。你能解釋一下嗎? – 390563959

回答

0

假設使用std :: list是一個需求(不確定是否來自你的問題),那麼Karoly在評論中指出,使用計數器來跟蹤你在鏈接列表中的位置。

void printLots(const std::list<int>& L, const std::list<int>& P) 
{ 
    std::list<int>::const_iterator it; 
    for (it = P.begin(); it != P.end(); ++it) 
    { 
    int indexRef = *it; 
    // You never know 
    if (indexRef < 0 || indexRef >= L.size()) continue; 
    std::list<int>::const_iterator it2; 
    int cntr = 0; 
    for (it2 = L.begin(); it2 != L.end(); ++it2) 
    { 
     if (cntr == indexRef) 
     { 
     std::cout << *it2 << std::endl; 
     break; 
     } 
     cntr++; 
    } 
    } 
} 
+0

這不會很有效率嗎? O(n)的實現是可能的嗎? – 390563959

0

這裏有一個想法:

#include <list> 
#include <iostream> 

typedef std::list<int> list_of_int; 

void print(const list_of_int& L, const list_of_int& P) 
{ 
    int p = 0; 
    for (list_of_int::const_iterator i = L.begin(), j = P.begin(); i != L.end(); ++i, ++p) 
    { 
    if (p == *j) 
    { 
     std::cout << *i << ' '; 
     ++j; 
    } 
    } 
} 

int main() 
{ 
    list_of_int 
    L = {0, 10, 20, 30, 40, 50, 60} 
    , P = {2, 4, 5}; 
    print(L, P); 
    return 0; 
} 

試試吧here

相關問題