如何循环结构对象?

时间:2013-11-21 14:27:26

标签: c++ for-loop struct

我正在编写一个程序,它使用结构的元素并对它们进行比较。

    void main()
{   struct data
        { string name;   float dep_score;
        };
      data a;//definining elements of my struct
      data b;
      data c;
      data d;
      data e;
      data f;

     a.name="australia";
     a.dep_score=5.8;
     b.name="canada";
     b.dep_score=7.9;
     c.name="United Kingdom";
     c.dep_score=6.6;
     d.name="United States";
     d.dep_score=10;
     e.name="japan";
     e.dep_score=3.6;
     f.name="france";
     f.dep_score=8.5;// values of the elements
    char i=a;
    char g;
    for (i=a;i<g;i++)//what I want to do..compare the scores of two struct objects 

        { if((i.dep_score+[i+1].dep_score) <=15)
            { cout<< i.name, (i+1).name;

                }

          }
    getch();
}

问题是我在'for'循环中遇到错误。 1.çhará'无法定义,'数据'无法转换为'çhar' 2.无法将结构元素与&lt; =

进行比较

尝试使用数字解析它。我可以用什么来解决此错误?

2 个答案:

答案 0 :(得分:0)

尝试

data a[10];

a[0].name = "x";
a[0].dep_score = 1.0;
....

for (int i = 0; i < 9; i++)
   if (a[i].dep_score < a[i+1].dep_score) ....

可能你还需要修理更多东西。

答案 1 :(得分:0)

这是一个如何使用容器以c ++方式完成的示例:

#include <iostream>
#include <string>
#include <vector>


int main()
{
    struct Data
    {
        std::string name;
        float score;
    };
    typedef std::vector<Data> CountryScores;
    CountryScores scores = { { "australia", 5.8f },
                             {"canada", 7.9f },
                             { "united kingdom", 6.6f },
                             { "united states", 10.0f },
                             { "japan", 3.6f },
                             { "france", 8.5f }
                           };
    if (! scores.empty()) //std::prev(scores.end()) is invalid for empty containers
    {
        for (auto it = scores.begin(); it != std::prev(scores.end()); ++it)
        {
            if (it->score + std::next(it)->score <= 15.f)
            {
                std::cout << "countries " << it->name << " and " << std::next(it)->name << " have low combined scores" << std::endl;
            }
        }
    }
}