#include<iostream>
#include<string>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;
struct Pizz
{
string name;
double zhijin;
double zhongliang;
};
typedef vector<Pizz> vp;
void show(Pizz P);
void input(vp &p);
int main()
{
vp p;
input(p);
for_each(p.begin(), p.end(), show);
return 0;
}
void input(vp &p)
{
string name;
double zhongliang;
double zhijing;
char is;
while (1)
{
cout << “请输入披萨的公司 : “;
cin >> name;
cout << “请输入披萨的直径 : “;
cin >> zhijing;
cout << “请输入披萨的重量 : “;
cin >> zhongliang;
p.push_back({name,zhijing,zhongliang});
cout << “请选择能否继续输入,继续请输入Y(Yes),否则输入N(No)” << endl;
cin >> is;
if (is == “Y”)
continue;
else
break;
}
}
void show(Pizz P)
{
cout << “公司是 ” << P.name << endl;
cout << “直径是 ” << P.zhijin << endl;
cout << “重量是 ” << P.zhongliang << endl;
cout << endl;
}
本人想在show()里进行编号,就是在用for_each进行遍历的时候进行编号1,2,3,4,这样的
#include<string>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;
struct Pizz
{
string name;
double zhijin;
double zhongliang;
};
typedef vector<Pizz> vp;
void show(Pizz P);
void input(vp &p);
int main()
{
vp p;
input(p);
for_each(p.begin(), p.end(), show);
return 0;
}
void input(vp &p)
{
string name;
double zhongliang;
double zhijing;
char is;
while (1)
{
cout << “请输入披萨的公司 : “;
cin >> name;
cout << “请输入披萨的直径 : “;
cin >> zhijing;
cout << “请输入披萨的重量 : “;
cin >> zhongliang;
p.push_back({name,zhijing,zhongliang});
cout << “请选择能否继续输入,继续请输入Y(Yes),否则输入N(No)” << endl;
cin >> is;
if (is == “Y”)
continue;
else
break;
}
}
void show(Pizz P)
{
cout << “公司是 ” << P.name << endl;
cout << “直径是 ” << P.zhijin << endl;
cout << “重量是 ” << P.zhongliang << endl;
cout << endl;
}
本人想在show()里进行编号,就是在用for_each进行遍历的时候进行编号1,2,3,4,这样的
解决方案
5
void show(const vp& P, size_t index) { for(size_t i = 0; i < P.size(); i++) { cout << "index=" << index <<endl; cout << "公司是 " << P[i].name << endl; cout << "直径是 " << P[i].zhijin << endl; cout << "重量是 " << P[i].zhongliang << endl; cout << endl; } }
5
//for_each(p.begin(), p.end(), show); //=> show(vp); //... //... void show(const vp& ps) { for(size_t i = 0; i < ps.size(); i++) { cout << "编号是 " << i << endl; cout << "公司是 " << P[i].name << endl; cout << "直径是 " << P[i].zhijin << endl; cout << "重量是 " << P[i].zhongliang << endl; cout << endl; } }
10
size_t不好理解的话,改成int型好了, i < (int) P.size(). 看起来就明白了。