2012-09-06 77 views
4

的向量的第二元件上獲得的迭代器,有在碼長和速度方面的快速方式獲得:在C++中,你如何我有<code>std::vector<std::pair<int,double>></code>對

  • 上的std::vector<double>鍵入問題時,第二個元素
  • 第二元件上的std::vector<double>::const_iterator而無需創建一個新的載體

我沒找到的問題列表類似的問題突出。

+0

至於你的問題稱號;如果你想要一個容器中的數據結構的內容的迭代器,你將不得不通過包裝一個標準的向量迭代器來編寫一個。我沒有看到你如何在不做iterate'n'copy的情況下實現你的第一個請求。我看不出你怎麼做第二個請求_at all_;你將需要一個自定義的迭代器。 – Rook

+0

@Rook:我實際上在尋找像ronag的解決方案。我應該編輯我的文章嗎? – BlueTrin

回答

6

對於第一個問題,您可以使用transform(在我的示例中使用C++ 11中的lambda)。 對於第二個問題,我認爲你不能擁有這個。

#include <vector> 
#include <string> 
#include <algorithm> 
#include <iostream> 

int main(int, char**) { 

    std::vector<std::pair<int,double>> a; 

    a.push_back(std::make_pair(1,3.14)); 
    a.push_back(std::make_pair(2, 2.718)); 

    std::vector<double> b(a.size()); 
    std::transform(a.begin(), a.end(), b.begin(), [](std::pair<int, double> p){return p.second;}); 
    for(double d : b) 
     std::cout << d << std::endl; 
    return 0; 
} 
1

我可以在那一刻想到的最簡單的將是這樣的:

std::vector<std::pair<int, double>> foo{ { 1, 0.1 }, { 2, 1.2 }, { 3, 2.3 } }; 

std::vector<double> bar; 
for (auto p : foo) 
    bar.emplace_back(p.second); 
6

我想你想的是一樣的東西:

std::vector<std::pair<int,double>> a; 

auto a_it = a | boost::adaptors::transformed([](const std::pair<int, double>& p){return p.second;}); 

,這將創造一個變換迭代通過容器(遍歷雙打),而不創建容器的副本。

+1

好吧,至少有一點要提到,這需要一個名爲* boost *的外部庫,而不是在代碼示例中使用未知的未知名稱。 –

+0

@ChristianRau:這種說法本身不對嗎? '提振::'。 – ronag

+0

是的,因爲他已經聽說過* boost *(這的確很可能,我承認)。 –

0

我的方式:

std::pair<int,double> p; 
std::vector<std::pair<int,double>> vv; 
std::vector<std::pair<int,double>>::iterator ivv; 

for (int count=1; count < 10; count++) 
{ 
    p.first = count; 
    p.second = 2.34 * count; 
    vv.push_back(p); 
} 

ivv = vv.begin(); 
for (; ivv != vv.end(); ivv++) 
{ 
    printf ("first : %d second : %f", (*ivv).first, (*ivv).second); 
} 
+4

我不認爲你回答這個問題... –

相關問題