【问题标题】:list of structures, to be sorted or searched (C++) [closed]要排序或搜索的结构列表(C++)[关闭]
【发布时间】:2013-12-15 09:22:34
【问题描述】:

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

【问题讨论】:

  • 欢迎来到 Stack Overflow!当询问“我如何”代码问题时,您应该尝试发布示例代码来展示您遇到的问题以及您尝试过的内容,最好以small, self-contained compilable example 的形式发布。如需更多帮助,请参阅How To Ask a Question 常见问题解答。
  • 使用std::find 而不是std::search
  • 我一定会在未来。 kfsone

标签: c++ list search stl structure


【解决方案1】:

如果我理解的话,你有一个结构 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

【讨论】:

    猜你喜欢
    • 2011-03-12
    • 2021-08-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多