c++ - std::vector inserting std::pair -


i having trouble trying insert std::pair in std::vector, code:

template <class r> class avectorcontainner { public:   avectorcontainner()        {          mvector= new std::vector<entry>;        }   typedef std::pair<int ,r *> entry;    void insert(r* apointer, int aid)   {      entry aentry;      aentry=std::make_pair(aid,apointer );      mvector->push_back(aentry);    } private:    std::vector<entry> * mvector; } 

this part of main file, declare pointer of class , used in initialization of template class.

in main.cpp:

    int main()     {         sometype * atipe= new sometype;         int aid=1;         avectorcontainer<sometype> * acontainer= new avectorcontainer;         acontainer->insert(atipe,aid);//error line delete atipe; delete acontainer;         return 0;     } 

compiler output:

error: non-static reference member 'const int& std::pair<const int&, sometype *>::first', can't use default assignment operator  error: value-initialization of reference type 'const int&' 

the original poster failed post code causing problem.

he has since edited post correct code demonstrates problem. code demonstrates problem follows:

template <class r, typename b=int> class avectorcontainer { public:   avectorcontainer() {}   typedef r* ptr_type;   typedef const b & const_ref_type;   typedef std::pair<const_ref_type ,ptr_type> entry;     void insert(ptr_type apointer, const_ref_type aid) {      entry aentry=std::make_pair(aid,apointer);      mvector.push_back(aentry);   } private:   std::vector<entry> mvector; };  class sometype { public:   sometype(){ x=5; }   ~sometype(){ }   int x; };  int main() {   sometype * atipe= new sometype;   int aid=1;   avectorcontainer<sometype> acontainer;   acontainer.insert(atipe,aid);   return 0; } 

compiler output:

/usr/include/c++/4.7/bits/stl_pair.h:88: error: non-static reference member 'const int& std::pair<const int&, sometype*>::first', can't use default assignment operator 

the flaw in these lines:

  typedef r* ptr_type;   typedef const b & const_ref_type;   typedef std::pair<const_ref_type ,ptr_type> entry;   std::vector<entry> mvector; 

here, original poster attempts make vector of pairs contain constant reference, , this:

entry aentry; aentry=std::make_pair(aid,apointer ) 

this attempts assign 1 pair another. const& variables cannot assigned -- can constructed (initialized) const&, not assigned.

an easy fix is:

entry aentry=std::make_pair(aid,apointer ) 

so not constructing aentry entry, instead of default constructing aentry (which illegal: const& must initialized), assigning it.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -