2014-01-21 95 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