【问题标题】:how to loop over vector size C++如何循环向量大小C++
【发布时间】:2014-01-21 06:04:41
【问题描述】:

我是 C++ 编程新手,对向量大小和 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 和 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)
    }

【问题讨论】:

  • 使用 vector 作为 age ,或者更好的 struct dataunit{ int age;string name ;string location ...} 然后 vector ,加上你想要比较的内容和方式。你想要达到的目标

标签: c++ loops vector


【解决方案1】:

您的示例不是您应该如何使用 C++。创建一个包含整数年龄、布尔或枚举性别和字符串位置的类/结构作为私有成员。这些成员应该可以通过 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;

【讨论】:

  • 我不太确定如何创建一个类,因为我是 C++ 新手。我不确定它们是如何工作的
  • @Kara 几乎每个 C++ 教程都解释了如何创建一个类,例如。 G。 cplusplus.com/doc/tutorial/classes
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多