2014-01-21 66 views
0

我是C++编程新手,对矢量大小和循环有疑问。如何遍历矢量大小C++

比方说,我的矢量大小是由值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 &ž比较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) 
    } 
+2

采用矢量 {INT年龄;字符串名称;字符串位置...}然后载体,再加上正确的是什么,以及如何你:在它的创建人people和环矢量想要比较和你试图实现什么 – qwr

回答

1

你举的例子是不是你应该如何使用C++的工作。创建一个包含int age,bool或枚举性别和字符串位置的类/结构作为私有成员。这些成员应该可以通过像int getAge()void setAge(int newAge)这样的方法访问。 这将促进您的原始任务很多。年龄,或更好的结构dataunit

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; 
+0

我不确定如何创建一个类,因为我是新来的C++。我不确定它们是如何工作的 – Kara

+0

@Kara几乎每个C++教程都解释了如何创建一个类, G。 http://www.cplusplus.com/doc/tutorial/classes/ – usr1234567