我正在尝试制作一个程序,要在其中复制一个已经定义的向量到另一个,但是在另一个继承的类中。就像这样:
//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();
};
此时,pants.cpp为空。当我尝试使用startPop = cityMap, copy()
或声明startPop(cityMap)
即使有时编译也要复制它时,在运行试图复制矢量的构造函数后,出现了段错误(核心转储)错误。就像“人口”类没有访问cityMap矢量的权限一样,即使我已经将其公开。我真的不知道如何使它起作用,所以请帮助我。哦,正确分配了cityMap
有多个选项可将一个向量复制到另一向量。
您可以使用std::copy
算法,但需要包含algorithm
头文件:
#include<algorithm>
std::copy(cityMap.begin(),cityMap.end(),std::back_inserter(startPop));
或者,您可以startPop
使用复制构造函数进行构造,如下所示:
startPop(cityMap);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句