Well, Here is the C++ code I’ve got here and cant compile
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int n = 900;
class City{
string name;
double area;
int count, roads;
public:
City() {}
City(string a, double b, int c, int d ) { a=name; b=area; c=count; d=roads;}
string getname() {return name;}
double getarea() {return area;}
int getcount() {return count;}
int getroads() {return roads;}
friend ostream& operator << (ostream& , City& );
friend istream& operator >> (istream& , City& );
};
ostream& operator << (ostream& out, City& a) {
out<<"name "<<a.name<<", area "<<a.area<<", count "<<a.count<< ", roads "<<a.roads<<endl;
return out;
}
istream& operator >> (istream& in, City& a) {
in>>a.name>>a.area>>a.count>>a.roads;
return in;
}
void fill(int arr[], int size){
ifstream ifs("cities.txt.");
for (int i=0;i<size;i++)
ifs>>arr[i];
}
void func(City* arr){
ofstream ofs("density.out");
for(int i=0;i<n;i++){
if(arr[i].getcount()/arr[i].getarea()>1000)
ofs<<arr[i];
}
}
int main(){
City* hm;
hm = new City[n];
fill(hm, n);
func(hm);
system ("pause");
return 0;
}
here is the error I get while compiling:
error C2664: ‘fill’ : cannot convert parameter 1 from ‘City *’ to ‘int
[]’
somehow I see that, it says something is wrong with the Class ‘City *” and int[] array, but can’t figure out. I change the ‘int’ with double but same prob.
that’s problem, otherwise it seems a simple array filling function from file.
any idea what’s wrong with it?
So, how would
void fill(City& arr, int size)
‘s body would like?
void fill(int arr[], int size)means that you need to pass an array ofinttofill. However, you are passing it an instance ofCity, specificallyhmin your main.I am assuming that you are trying to read in a list of
Citydescriptions fromcities.txt(and thus have appropriate stream extraction/insertion operators). Change the signature offillto accept a pointer toCityobjects so that you can fill in an array ofCityobjects and notints.Make sure that the argument you pass to
fillin main is a properly allocated array ofCityobjects of size at leastszwhereszis what you pass in as the second parameter. Keep in mind to calldelete []to free this array that you create.A more idiomatic approach would be to use
vector<City>so that you don’t have to worry about memory management issues. Your modifiedfillsignature would then be:You will need to
#include <vector>in order to be able to usevector<City>though.Finally, to take advantage of RVO, simply return a
vector<City>by value instead of passing it in as a parameter. So, you’d do something like: