简体   繁体   English

类访问推送中的STL向量

[英]STL vector inside the class access push

What is the syntax to push integer into vector, which is inside Custothe class? 将整数推入矢量(在Custothe类内部)的语法是什么?

class Customer {
vector <int> loyalID;
}

int main {
Customer customer;

vector<Customer>customers;

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

Either make the vector public (which is not recommended) or write a public member function in the class: 可以将向量设为公共(不推荐使用),或者在类中编写公共成员函数:

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

In main once you have elements in customers you could write something like this: main ,一旦你在元素customers ,你可以写这样的事情:

customers[0].push_back(10);

loyalID is a private field of Customer . loyalIDCustomer的私有字段。 Either make it public (not recommended), or add a public method: 使其公开(不建议使用),或添加公共方法:

class Customer {
  vector <int> loyalID;

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

Accessing loyal ids: 访问会员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(); }
}

Usage: 用法:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM