如何循环矢量大小C ++

时间:2014-01-21 06:04:42

标签: c++ loops vector

我是C ++编程的新手,对于Vector size和for循环有疑问。

假设我的矢量大小为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和amp;来生成每个年龄段。 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)
    }

1 个答案:

答案 0 :(得分:1)

您的示例不是您应该如何使用C ++。创建一个包含int age,bool或enum性别和字符串位置的类/结构作为私有成员。这些成员应该可以通过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;