hrq
hrq

Reputation: 23

How can I copy one vector to another through different classes

I'm trying to make a program in which I want to copy one already defined vector to another, but in different, inherited class. It's something like 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 is empty at this moment. When I'm trying to copy it using startPop = cityMap, copy() or declaring startPop(cityMap) even though sometimes it compiles, after running constructor in which I try to copy vectors I've got segmentation fault(core dumped) error. It's just like Populations class doesn't have an access to cityMap vector, even though I already made it public. I'm really out of ideas how to make it work, so please, help me. Oh and cityMap is assigned corretly

Upvotes: 1

Views: 1443

Answers (1)

Steephen
Steephen

Reputation: 15844

There are multiple options to copy one vector to another.

You can use std::copy algorithm, but need to include algorithm header file:

#include<algorithm>
std::copy(cityMap.begin(),cityMap.end(),std::back_inserter(startPop));

Or you can construct startPop using copy constructor as follows:

startPop(cityMap);

Upvotes: 1

Related Questions