要排序或搜索的结构列表(C ++)

时间:2013-11-29 08:33:52

标签: c++ list search stl structure

我有一个结构列表(结构有名称和编号参数(两者都是字符串类型))。 我需要在列表中搜索用户输入的给定字符串(名称或数字)的所有匹配项。 我试图使用std :: search,但我无法做到这一点。 有没有办法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

如果我理解,你有一个结构A和一个A的对象列表,所以:

struct A {
  string name;
  int num;
}

class B {
  public:
    list<A>::iterator findName(const string& n) {
      list<A>::iterator it = listOfA.begin();
      for(; it != listOfA.end(); ++it) {
         if((*it).name == n) {
           return it;
         }
      }
      return 0; 
    }
    list<A>::iterator findNum(const int& n) {
      list<A>::iterator it = listOfA.begin();
      for(; it != listOfA.end(); ++it) {
         if((*it).num == n) {
           return it;
         }
      }
      return 0; 
    } 
  private:
    list<A> listOfA;
 }      

对于列表的排序,有很多方法;例如,您可以看到here