Eda Yıldırım Eda Yıldırım - 6 months ago 34
C++ Question

c++ get a vector from a map of vectors

I have a map of vector

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

I want to get the vector paired with a specific key, such as:

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

The error I get is:

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

I tried below, didn't work:

&vec = hit[1];

error: expression is not assignable

I also tried below, didn't work:

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

error: expression is not assignable

Does anyone know why these doesn't work, and how I can get the vector from the map?

Thanks a lot in advance

Here is what getAlignedHits does and the variables I used there:

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;
hit[i] = bla;

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



The following works for me

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

or simpler

auto & h0 = hit[0];

A full example

#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];


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

   return 0;