2016-08-03 53 views
-5

我有地圖的矢量的C++從地圖矢量得到的矢量

map< int, vector<float> > hit = getAlignedHits(); 

我想獲得與特定鍵配對的載體,如:

vector<float> vec; 
vec = hit[1]; 

錯誤我得到的是:

candidate function not viable: no known conversion from vector<float, allocator<float>> to const vector<double, allocator<double>> for 1st argument vector& operator=(const vector& __x);

我嘗試以下,沒有工作:

&vec = hit[1]; 

error: expression is not assignable

我也試過以下,沒有工作:

map< int, vector<float> >::iterator itr; 
    itr = hit.find(1); 
    &vec = itr->second; 

error: expression is not assignable

有誰知道爲什麼這些不工作,我怎麼能得到從地圖矢量?

感謝很多提前

編輯: 這裏是getAlignedHits確實和變量我使用的有:

const int NLayer = 6;, vector<float> *hit_position; double alignmentpar[NLayer]; 


map< int, vector<float> > getAlignedHits(){ 
    double newpos; 
    for (int i=0; i<NLayer; i++) { 
     vector<float> bla; 
     bla.clear(); 
     hit[i] = bla; 
    } 

    for (unsigned int ihit=0; ihit<layerID->size(); ihit++) { 
     newpos = hit_position->at(ihit) - alignmentpar[layerID->at(ihit)]; 
     hit[layerID->at(ihit)].push_back(newpos); 
    } 

} 
+0

不應該'VEC以下作品 - itr->第二;'工作?此外,錯誤似乎表明你正在調用一些'const'方法,另外你應該總是將'find'返回的迭代器與map的'end()'進行比較:if(itr!= hit.end() )vec = itr-> second;' – EdChum

+4

我相信還有別的東西,你不會告訴我們這會導致這個錯誤。這看起來很好。 – DimChtz

+3

@EdChum看看你的錯誤消息,你的示例代碼與錯誤不匹配。錯誤說你正在做矢量 vec; map >命中; vec = hit [1];' – PeterT

回答

0

std::vector<float> & h0 = hit[0]; 

或簡單

auto & h0 = hit[0]; 

完整的例子

#include <map> 
#include <vector> 
#include <iostream> 

int main() 
{ 
    std::map< int, std::vector<float> > hit { { 0, {} } }; 

    std::vector<float> & h0a = hit[0]; 
    auto & h0b = hit[0]; 

    h0a.push_back(2.3); 

    std::cout << hit[0].front() << std::endl; 
    std::cout << h0a.front() << std::endl; 
    std::cout << h0b.front() << std::endl; 

    return 0; 
} 
+0

是的,它的工作原理。但爲什麼OP有錯誤? – StoryTeller

+0

@storyTeller - 我懷疑他正在做類似'std :: vector vec; &vec = hit [0];' – max66

+0

是的,我在做那個:),修正了它,std :: vector &h0a = hit [0];工作。非常感謝! –

1

當然,

&vec = ... <something> 

將無法​​正常工作,因爲你不能指定變量的地址,但是:

candidate function not viable: no known conversion from 'vector>' to 'const vector>' for 1st argument vector& operator=(const vector& __x);

給我一種感覺,你正試圖在const函數中執行此賦值,或者在對其應用某個常量的對象上執行此賦值。請分享更多「原始」代碼,以便我們發現錯誤。

+1

看看他的評論的來源,實際的錯誤說'從'vector >'轉換爲'const vector >' – PeterT

+1

@PeterT幹嘛?我沒有在OP中看到任何提及「雙」的情況。我甚至在網頁上進行了文字搜索。 – StoryTeller

+2

@StoryTeller這是因爲stackoverflow標記吞噬了它,點擊他的問題上的「編輯」,你會看到 – PeterT