2014-01-21 2 views
0

저는 C++ 프로그래밍을 처음 접했고 벡터 크기와 for 루프에 대해 질문이 있습니다.벡터 크기를 반복하는 방법 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 

내가 X에 Y & Z를 비교하여 연령의 각을 생성 루프를 만들려고합니다. 그래서

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

사용 벡터 을 나이, 또는 더 나은 구조체 dataunit에 대한 {INT 연령, 문자열 이름을, 문자열 위치 ...} 다음 벡터 , 플러스 올바른을 무엇을 어떻게 당신을 compare.and을 얻으 려합니다. – qwr

답변

1

귀하의 예제는 C++와 함께 작동하는 방법이 아니다. int age, bool 또는 enum gender와 문자열 위치를 private 멤버로 포함하는 클래스/구조체를 만듭니다. 이러한 멤버는 int getAge()void setAge(int newAge)과 같은 메서드를 통해 액세스 할 수 있어야합니다. 원래 작업을 쉽게 할 수 있습니다. 그 위에 사람 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; 
+0

저는 C++을 처음 접한 이후로 클래스를 만드는 방법을 알지 못합니다. 어떻게 작동하는지 모르겠습니다. – Kara

+0

@Kara 사실상 모든 C++ 자습서에서는 클래스를 만드는 방법을 설명합니다. e. 지. http://www.cplusplus.com/doc/tutorial/classes/ – usr1234567