c++ - How can I copy one vector to another through different classes -
i'm trying make program in want copy 1 defined vector another, in different, inherited class. it's this:
//map.cpp void map::setquantity() { std::cout << "set quantity: "; std::cin >> quantity; } void map::setarray(){ for(int i=0;i<quantity;++i) { citymap.push_back(city()); } } void map::showmap(){ for(int i=0;i<quantity;++i){ citymap[i].showcoords(); } } double map::getlength(int a, int b) { return sqrt(pow(citymap[a-1].getcoordx()-citymap[b-1].getcoordx(),2)+pow(citymap[a-1].getcoordy()-citymap[b-1].getcoordy(),2)); } int map::getquantity() { return quantity; } map::map() { } map::~map() { } //city.cpp int city::randomize(int range) { return rand()%range + 1; } void city::setcoords(){ coord_x = randomize(1000); coord_y = randomize(1000); } void city::showcoords(){ std::cout << "x = " << coord_x << " y = " << coord_y << std::endl; } int city::getcoordx(){ return coord_x; } int city::getcoordy() { return coord_y; } city::city(){ setcoords(); } //populations.h class populations: public map { protected: std::vector<city> startpop; std::vector<city> newpop; public: void showpop(); void setstartpopulation(); populations(); };
and populations.cpp empty @ moment. when i'm trying copy using startpop = citymap, copy()
or declaring startpop(citymap)
though compiles, after running constructor in try copy vectors i've got segmentation fault(core dumped) error. it's populations class doesn't have access citymap vector, though made public. i'm out of ideas how make work, please, me. oh , citymap assigned corretly
there multiple options copy 1 vector another.
you can use std::copy
algorithm, need include algorithm
header file:
#include<algorithm> std::copy(citymap.begin(),citymap.end(),std::back_inserter(startpop));
or can construct startpop
using copy constructor follows:
startpop(citymap);
Comments
Post a Comment