简体   繁体   English

如何从映射中打印出键和值作为 C++ 中的列表

[英]How to print out key and values from a map as a list in C++

I am trying to print out more than one record from a map that has a string and a pointer class.我试图从具有字符串和指针类的映射中打印出多个记录。 This is a follow up from this post: how to dereference a pointer of a map of pointers to objects in c++ .这是这篇文章的后续内容: how to dereference a pointer of a map of pointers to objects in c++ 1. I am having issues on pushing back an object class into a vector. 1. 我在将对象类推回向量时遇到问题。 2. I would like to print more than one record from a map. 2. 我想打印一张地图中的多个记录。

I have tried to use vectors but not sure if that's the way to go.我曾尝试使用向量,但不确定这是否可行。 I got some errors from it.我从中得到了一些错误。 I know in Java you can use array list so trying to refresh my c++.我知道在 Java 中你可以使用数组列表来尝试刷新我的 C++。 Any good examples you have following from above link solution.您从上述链接解决方案中获得的任何好的示例。

class Employee
{
    public:
    int  employeeID;

    Employee()
    {
       employeeID = 123;
    } 
 };
int main(int argc, char* argv[]) {
  std::map<std::string, Employee *> *_employeePayroll;
  std::map<std::string, Employee *> _employeeID;
  std::map<std::string, Employee *>::const_iterator itEmployeeID;

  _employeePayroll = &_employeeID;
  (*_employeePayroll)["Karl"] = new Employee;
  (*_employeePayroll)["George"] = new Employee;

  vector<std::string> v1;
  v1.push_back(itEmployeeID->first);
  // Here I am having issues on pushing back an object class into a 
  // vector.  maybe as follows:
  v1..push_back(itEmployeeID->second);
  v1.shrink_to_fit();
  for ( auto it = v1.begin(); it != v1.end(): it++ )
  {
     std::cout << *it;
     std::cout << std::endl;
  }

  return 0;
}

I would like to print out more than one record from a map that has a string and a pointer class.我想从具有字符串和指针类的映射中打印出多个记录。

You might do something like:您可能会执行以下操作:

int main() {
    std::map<std::string, Employee> employee {
       {"Karl", Employee{42}},
       {"George", Employee{59}},
    };

    for (const auto& p : employee ) {
        std::cout << p.first << std::endl; // "Karl", "George"
        // p.second is Employee object.
    }
}

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM