void distances(vector<string> &cities, vector<double> &xcoord, vector<double> &ycoord, vector<double> &dist)
// Function used to calculate the distances between the different cities and then storing it into a vector.
{
double dist1;
for (int i =0; i < cities.size(); i++)
{
for (int j =0; j < cities.size(); j++)
{
double dist1 = sqrt( ((xcoord.at(i) - xcoord.at(j))*(xcoord.at(i) - xcoord.at(j))) + ((ycoord.at(i) - ycoord.at(j))*(ycoord.at(i) - ycoord.at(j))) );
dist.push_back(dist1);
}
}
}
我正在使用此功能计算10个不同城市之间的距离。然后我将计算出的距离存储到矢量中。我现在想把它格式化成一个表格。我如何使用我创建的矢量来做到这一点?
答案 0 :(得分:1)
通过将其格式化为表格,是指将其排列为2D矢量,就好像它是一个表格一样?因为,你可以通过将dist作为2D向量而不是单维向量来传递。
你应该把dist作为向量的向量传递,初始化为9 x 9向量(或cities.size()x cities.size()向量),如下所示:
vector< vector< double > > vector_I_Intend_To_Pass_As_Argument; //Pass this vector as the dist argument when calling the distances method
vector_I_Intend_To_Pass_As_Argument = vector< vector< double > >(cities.size()); //Or just 9, if you want to hardcode it
for(int i = 0; i < cities.size(); i++)
{
vector_I_Intend_To_Pass_As_Argument[i] = vector< double >(cities.size());
}
vector< vector< double > > vector_I_Intend_To_Pass_As_Argument; //Pass this vector as the dist argument when calling the distances method
vector_I_Intend_To_Pass_As_Argument = vector< vector< double > >(cities.size()); //Or just 9, if you want to hardcode it
for(int i = 0; i < cities.size(); i++)
{
vector_I_Intend_To_Pass_As_Argument[i] = vector< double >(cities.size());
}