我正在尝试使用矢量erase
函数删除作为作业分配矢量元素的字符串。我曾尝试线两种方式:我不能从矢量中删除用户定义的值吗?
vectnames.erase(vectnames[blowup]);
vectnames.erase(blowup);
有谁知道为什么擦除功能可能无法正常工作?作为一个背景,我必须让用户输入一个星球名称作为矢量,并让它们按名称删除。我在网上找到的例子使用#2行,但它不工作...
这是我的代码的其余部分供参考。
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
class planet
{
private:
string n;
double d, m;
public:
void Density (double d, double m)
{
double Den = m/((4.0/3.0)*M_PI*pow((d/2.0), 3.0));
cout<<"Density: "<<Den<<endl;
}
void SurfaceArea(double d)
{
double S = 4.0*M_PI*pow((d/2.0), 2.0);
cout<<"Surface Area: "<<S<<endl;
}
void Name (string n)
{
string N = n;
cout<<"Name: "<<N<<endl;
}
void Gravity (double G, double m, double d)
{
double F = G*m/pow((d/2.0), 2.0);
cout<<"Force of gravity: "<<F<<endl;
}
};
int main()
{
const double G=6.67384e-11;
int c=0;
string n, N, blowup;
double d=0.0, m=0.0, Den=0.0, S=0.0, F=0.0;
vector<string> vectnames;
vector<double> vectdiam;
vector<double> vectmass;
do
{
cout<<"1. Add a planet\n";
cout<<"2. Delete planet\n";
cout<<"3. Find planet (by name)\n";
cout<<"4. List all planets\n";
cout<<"5. Sort (alphabetical order)\n";
cout<<"6. Quit\n";
cout<<endl;
cout<<"Please select an option from the menu above."<<endl;
cin>>c;
cout<<endl;
if(c==1)
{
planet red;
cout<<"Enter the planet's name: ";
cin>>n;
cout<<"Enter the planet's diameter: ";
cin>>d;
cout<<"Enter the planet's mass: ";
cin>>m;
cout<<endl;
vectnames.push_back(n);
vectdiam.push_back(d);
vectmass.push_back(m);
red.Name(n);
red.Density(d, m);
red.SurfaceArea(d/2.0);
red.Gravity(G, m, d);
cout<<endl;
}
else if (c==2)
{
cout<<"Fire the Death Star's superlaser at: "<<endl;
cin>>blowup;
vectnames.erase(vectnames[blowup]); //This is the part that I'm having trouble with
for (int i=0; i<vectnames.size(); i++)
{
cout<<vectnames[i]<<endl;
}
}
else if (c==4)
{
for (int i=0; i<vectnames.size(); i++)
{
planet red;
cout<<"Planet name: "<<vectnames[i]<<endl;
cout<<"Planet diameter: "<<vectdiam[i]<<endl;
cout<<"Planet mass: "<<vectmass[i]<<endl;
red.Density(vectdiam[i], vectmass[i]);
red.SurfaceArea(vectdiam[i]/2.0);
red.Gravity(G, vectmass[i], vectdiam[i]);
cout<<"************************"<<endl;
cout<<endl;
}
}
} while (c!=6);
system("pause");
return 0;
}
你的行星类没有使用任何数据成员,这三个向量应该是包含这三个属性的类的一个容器(比如你的'planet'类)。如果您需要删除名称,请考虑从地名到行星的地图。 – chris
@chris这将是我的下一个问题 - 如果我删除星球名称_我怎样才能确保其数据也被删除?_如何将三个向量放入“一个容器”?另外,我认为我正在使用数据记忆器,因为我的无效函数使用私有变量'n,d和m'。 – heyheythere
http://stackoverflow.com/questions/30135646/how-do-i-create-a-vector-that-the-user-can-keep-adding-values-to-between-menu-ch你再问一遍这里, –