将整数推送到vector中的语法是什么?在Custothe类中?
class Customer {
vector <int> loyalID;
}
int main {
Customer customer;
vector<Customer>customers;
customers.push_back(/*some integers to go into loyalID vector*/);
}
答案 0 :(得分:1)
将向量公开(不推荐)或在类中编写公共成员函数:
void Customer::push_back(int i)
{
loyalID.push_back(i);
}
在main
中,customers
中有元素后,您可以写下这样的内容:
customers[0].push_back(10);
答案 1 :(得分:1)
loyalID
是Customer
的私有字段。要么公开(不推荐),要么添加公共方法:
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"