gpt4 book ai didi

c++ - STL vector里面类访问推送

转载 作者:行者123 更新时间:2023-11-28 02:37:40 26 4
gpt4 key购买 nike

在 Custothe 类中将整数插入 vector 的语法是什么?

class Customer {
vector <int> loyalID;
}

int main {
Customer customer;

vector<Customer>customers;

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

最佳答案

loyalIDCustomer 的私有(private)字段。要么将其公开(不推荐),要么添加一个公共(public)方法:

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"

关于c++ - STL vector里面类访问推送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26958986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com