2011-06-03 249 views
0

使用std :: copy將1D矢量轉換爲2D矢量時,出現了編譯錯誤。將1D矢量轉換爲2D矢量

int main() 
{ 
    std::vector< std::vector<float> > v2D(10, std::vector<float>(10, 0.0)); 
    std::vector<float> v1D(100, 0.0); 

    for (int i = 0; i < 100; ++i) 
     v1D.push_back(i); 

    for (unsigned int j = 0; j < 10; j++) 
    { 
     std::copy(v1D.begin() + j * 10, v1D.begin() + (j + 1) * 10, std::back_inserter(v2D[j].begin())); 
    } 
} 

請您幫忙解決這個問題嗎?謝謝。

+0

錯誤信息是什麼意思? – 2011-06-03 02:31:50

回答

4

std::back_inserter需要一個容器,而不是迭代器。將std::back_inserter(v2D[j].begin())更改爲std::back_inserter(v2D[j])。請注意,這將在std::vector<float>v2D[j]處撥打.push_back(),因此您可能還需要將std::vector< std::vector<float> > v2D(10, std::vector<float>(10, 0.0));更改爲std::vector< std::vector<float> > v2D(10);

或者,您可以將std::back_inserter(v2D[j].begin())更改爲v2D[j].begin()。這是因爲std::copy需要輸出迭代器,並且std::vector<>::iterator表現爲vector<>中有足夠數量的元素要覆蓋時的行爲。這樣,你目前初始化的v2D已經是理想的了。


編輯:別人說,這在一個單獨的答案然後將其刪除,所以我會說這代表他們的,因爲這絕對是值得關注的:因爲你初始化v1D有100個元素,在[1 .. 100]數字然後push_back附加到最初的100個元素(它們都具有您指定的值0),而不是覆蓋它們。您應該將std::vector<float> v1D(100, 0.0);更改爲std::vector<float> v1D;以獲得您顯然想要的行爲(或者如果您真的關於效率迂腐,則爲std::vector<float> v1D; v1D.reserve(100);)。

+0

尊敬的ildjarn 感謝您發現th錯誤。 – GoldenLee 2011-06-03 02:49:10

+0

是的。我在測試過程中已經發現了這個問題。 – GoldenLee 2011-06-03 02:54:33