gpt4 book ai didi

c++ - 如何循环 vector 大小 C++

转载 作者:行者123 更新时间:2023-11-28 07:09:25 24 4
gpt4 key购买 nike

我是 C++ 编程新手,对 vector 大小和 for 循环有疑问。

假设我的 vector 大小为 3,包含以下值:

x = [Susan 13, Female, Chicago Illinois] //this will be the comparison point
y = [Sally 18, Female, Tokyo Japan]
z = [Rowland 2, Male, Arizona California] //y & z will be compared to x
+...other vectors depending on how many the user inputs

我想创建一个 for 循环,通过将 y 和 z 与 x 进行比较来生成每个年龄段。所以我希望它像

x[0] - y[0] --> 5  //difference of the ages
x[0] - z[0] --> 11

到目前为止,我有这个:

vector<string> age, gender, location;

void ageDiff(vector<string> a, vector<string> g, vector<string> l){
//i want to start calculating the age differences but i'm not sure how to loop depending on how many data the user inputs
}

int main(){
int n;
std::cout << "How many data will you input? ";
std::cin >> n;

for (a=0;a<n;a++){
std::cout << "Please enter the data for person #" << a;
std::cin >> a;
std::cin >> b;
std::cin >> c;
age.push_back(a);
gender.push_back(b);
location.push_back(c);

for (a=0;a<(age.size()-1);a++){
ageDiff(age, gender, location)
}

最佳答案

你的例子不是你应该如何使用 C++。创建一个包含 int age、bool 或 enum gender 和 string location 作为私有(private)成员的类/结构。这些成员应该可以通过 int getAge()void setAge(int newAge) 等方法访问。这将极大地促进您的原始任务。创建一个人 vector people 并对其进行循环:

for (size_type i = 0; i < people.size(); i++)
for (size_type j = i + 1; j < people.size(); j++)
std::cout << "age difference between " << i << " and " << j << " is "
<< std::abs(people[i].getAge() - people[j].getAge()) << "." << std::endl;

关于c++ - 如何循环 vector 大小 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21250375/

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