c++ - How to simple assign vectors of different structs? -


so have 2 different structs (a & b) same variables , overloaded = operator in struct b convert b.

i want able simple assign vector of a vector b, compiler gives me error:

main.cpp|61|error c2679: binary '=' : no operator found takes right-hand operand of type 'std::vector<_ty>' (or there no acceptable conversion)| 

i assumed had overloaded = operator , iterate on vector , use = operator each instance. how this?

here code:

#include <iostream> #include <vector> using namespace std;  struct {     int x, y;     a() {}     a(int _x, int _y)     {         x = _x;         y = _y;     } };  struct b {     int x, y;     b(){}     b(int _x, int _y)     {         x = _x;         y = _y;     }      b& operator=(const a& _a)     {         x = _a.x;         y = _a.y;         return *this;     } };  int main() {     a_test(1,2);      std::vector<a> a_vec;     std::vector<b> b_vec;      for(int = 0; <10; i++)     {         a_vec.push_back(a_test);     }      /*     for(int = 0; i<a_vec.size(); i++)     {         b_vec.push_back(a_vec[i]);     }     */      b_vec = a_vec;      return 0; } 

the problem operator= works on individual elements, not on whole vectors.

you need define constructor converts a b.

then can use std::vector::assign rather std::vector::operator=.

#include <iostream> #include <vector> using namespace std;  struct {     int x, y;     a(): x(0), y(0) {}     a(int x, int y): x(x), y(y) {} };  struct b {     int x, y;     b(): x(0), y(0) {}     b(int x, int y): x(x), y(y) {}      // need construct b     b(const a& a): x(a.x), y(a.y) {}      b& operator=(const a& a)     {         x = a.x;         y = a.y;         return *this;     } };  int main() {     a_test(1,2);      std::vector<a> a_vec;     std::vector<b> b_vec;      for(int = 0; <10; i++)     {         a_vec.push_back(a_test);     }      // b_vec = a_vec; // not     b_vec.assign(a_vec.begin(), a_vec.end()); //      return 0; } 

note: changed of names because c++ standard says should not begin variable names underscore '_'.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -