【问题标题】:STL vector inside the class access push类访问推送中的 STL 向量
【发布时间】:2014-11-16 16:05:52
【问题描述】:

将整数推入向量的语法是什么,在 Custothe 类中?

class Customer {
vector <int> loyalID;
}

int main {
Customer customer;

vector<Customer>customers;

customers.push_back(/*some integers to go into loyalID vector*/);
}

【问题讨论】:

  • customersCustomer 的向量,而不是int 的向量。您可以将Customers 推到它上面,而不是ints。您可以将ints 推送到customer.loyalID 上(或者如果它不是私人的也可以)。再说一遍,你想做什么?
  • @IgorTandetnik 为每个客户存储 uniqueID(比如客户拥有的会员卡),当我访问特定客户时,显示这些 un​​iqueID。

标签: c++ class vector stl


【解决方案1】:

loyalIDCustomer 的私有字段。要么公开(不推荐),要么添加公共方法:

class Customer {
  vector <int> loyalID;

  public:
  void addLoyalId(int id)
  {
    loyalID.push_back(id);
  }
}

访问忠诚 ID:

class Customer {
  vector <int> loyalID;

  public:
  void addLoyalId(int id)
  {
    loyalID.push_back(id);
  }

  std::vector<int>::iterator begin() const { return _loyalID.begin(); }
  std::vector<int>::iterator end() const { return _loyalID.end(); }
}

用法:

Customer c;
c.addLoyalId(1);
c.addLoyalId(2);
c.addLoyalId(3);

for (auto&& id : c)
{
  std::cout << id << " ";
} // will print "1 2 3"

【讨论】:

  • 如果我想为每个客户存储多个loyalID,它也可以吗?如果是这样,我该如何访问?
【解决方案2】:

要么将向量公开(不推荐),要么在类中编写公共成员函数:

void Customer::push_back(int i)
{
    loyalID.push_back(i);
}

main 中,一旦你在customers 中有元素,你就可以这样写:

customers[0].push_back(10);

【讨论】:

  • customers 此时为空; customers[0] 表现出未定义的行为。
  • 我刚刚提供了应该如何使用成员函数的示例。做了澄清。
猜你喜欢
  • 1970-01-01
  • 2011-11-22
  • 2010-12-15
  • 2011-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
相关资源
最近更新 更多