c++ - 向量在结构中无法正常工作
问题描述
我声明了一个vector<string>
,我什至无法编译它。我尝试了很多方法,但都没有奏效。我正在尝试写出 x.surname.push_back(word)[i] 但它确实写错了,我不知道如何正确编写它并使其可以编译。
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number, i = 0;
string word;
struct donators {
vector<string> surname;
vector<int> amount;
} x;
cout << "How many donators do you want to register? " << endl;
cin >> number;
for (i = 0; i < number; i++) {
cout << "Surname: ";
cin >> word;
x.surname.push_back(word)[i];
cout << "Amount: ";
x.amount.push_back(i);
cin >> x.amount[i];
}
cout << "OUR GORGEUS DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] >= 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
}
else if (x.amount[i] < 10000) {
cout << "Lack of surnames!" << endl;
}
}
cout << "OUR CASUAL DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] < 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
} else if (x.amount[i] >= 10000) {
cout << "Lack of surnames!" << endl;
}
}
return 0;
}
还有一件事情。如何造句“没有姓氏!” 写一次?在某些情况下,它会被写出两次或更多次多余的内容。
解决方案
您[i]
在代码中放置看似随机的位置。比如在x.surname.push_back(word)[i];
. 如果您不确定它们在做什么,请不要将此类内容添加到您的代码中。
构造x.surname(word)[i]
也是错误的。x.surname(word)
应该是什么?此语法用于函数调用。surname
但是,它不是函数。这是一个std::vector<std::string>
。换一个就x.surname[i]
行了。
还有一件事情。如何造句“没有姓氏!” 写一次?在某些情况下,它会被写出两次或更多次多余的内容。
那是因为您为每个不符合标准的捐赠者编写了它。相反,跟踪是否有任何捐赠者符合标准,并且仅在没有最终符合标准时才打印。你可以这样做:
bool HasGorgeousDonators = false;
然后在循环中:
if (x.amount[i] >= 10000)
{
cout << "Surname: " << x.surname[i];
cout << "Amount: " << x.amount[i] << endl;
HasGorgeousDonators = true;
}
在循环之后:
if (!HasGorgeousDonators)
cout << "Lack of surnames!" << endl;
另一个循环也是如此。另外,请考虑以下问答:
推荐阅读
- javascript - 如何使用该 div id 内的按钮将“getelementbyid”值设置为 div id
- javascript - 如何使用 react-hook-form 中的单选按钮控制带有错误验证的表单?
- python - Flask Restful 根据请求正文中的数据以 XML 或 JSON 格式响应
- python - bs4 无法使用 id 找到具有特定类的 div
- typescript - 如何在 vscode 扩展中通过正则表达式找到一个单词并找出它的范围和位置
- javascript - Discord.js 删除消息而不是命令
- raspberry-pi3 - Raspberry pi 3B+ 上的 AVS 设置冻结在 95%
- javascript - 在 HoC 参数中使用 props
- flutter - 颤动如何在GetView类中实现动画
- r - R: create a data.frame or data.table from a list and unpacked list of lists