首页 > 解决方案 > 向量在结构中无法正常工作

问题描述

我声明了一个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;
}

还有一件事情。如何造句“没有姓氏!” 写一次?在某些情况下,它会被写出两次或更多次多余的内容。

标签: c++stringvectorstruct

解决方案


[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;

另一个循环也是如此。另外,请考虑以下问答:

为什么是“使用命名空间标准;” 被认为是不好的做法?


推荐阅读