【发布时间】:2022-01-01 09:08:55
【问题描述】:
struct Article
{
int Id;
string name;
string desc;
double price;
Article(int s, string n, string o, double c)
{
Id = s;
name = n;
desc = o;
price = c;
}
};
vector <Article> vArticle;
void GiveName(vector <Article> vArticle);
int main()
{
vector <Article> vArticle;
Article a1(1, "Banana", "Fruit", 7.99);
Article a2(2, "Apple", "Fruit", 5);
Article a3(3, "Book", "Bible", 309.99);
Article a4(4, "Laptop", "Laptop Lenovo", 4989.99);
Article a5(5, "Banana", "Fruit ", 5.99);
vArticle.push_back(a1);
vArticle.push_back(a2);
vArticle.push_back(a3);
vArticle.push_back(a4);
vArticle.push_back(a5);
GiveName(vArticle);
}
void GiveName(vector <Article> vArticle)
{
vector <Article> vInput;
cout << "List of articles: " << endl;
for (int i = 0; i < vArticle.size(); i++)
{
cout << vArticle[i].Id << ", " << vArticle[i].name << ", " << vArticle[i].desc << ", " << vArticle[i].price << endl;
}
cout << "\n\n\n";
cout << "Enter an article name" << endl;
string input;
cin >> input;
for (int i = 0; i < vArticle.size(); i++)
{
if (vArticle[i].name == input)
{
cout << vArticle[i].Id << ", " << vArticle[i].name << ", " << vArticle[i].desc << ", " << vArticle[i].price << endl;
}
else
{
cout << "Article not found" << endl;
}
} }
由于使用 for 循环,我的代码为每个不等于输入的成员显示“找不到文章”。 让它显示的最佳方式是什么,例如,如果我写“香蕉”,它只显示包含名称香蕉的元素。 如果没有任何元素包含它,则显示“找不到文章”?
【问题讨论】:
-
顺便说一句。在 GiveName 中按值传递向量会强制进行深层复制。最好以
vector<Article>&传递。你有三个 vArticle 声明:一个是全局范围的,一个是本地的,一个是本地的,一个是本地的 GiveName ...
标签: c++ loops if-statement vector