简体   繁体   中英

how to loop over vector size C++

I am new to C++ programming and have a question about Vector size and for loops.

Let's say that my Vector size is 3 containing the values:

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

I want to create a for loop that will generate each of the ages by comparing y & z to x. So I want it to be like

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

So far, I have this:

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)
    }

Your example is not how you should work with C++. Create a class / struct containing int age, bool or enum gender and string location as private members. These members should be accessible by methods like int getAge() and void setAge(int newAge) . That will facilitate your original task a lot. Create a vector of people people and loop over it:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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