简体   繁体   English

在C ++中包含类对象的迭代映射

[英]Iterating map in C++ containing class objects

I am creating a map in C++ which contains a integer key and the value is an object of class User. 我正在C ++中创建一个包含整数键的映射,该映射的值是User类的对象。 I am able to insert the object into the map with the following code - 我可以使用以下代码将对象插入地图-

std::map<std::string,User>::iterator it = usermap.begin();
        usermap.insert (it, std::pair<string,User>(object.userid,object));

The code I am using to write the objects in a .bin file is - 我用来在.bin文件中写入对象的代码是-

map<std::string, User>::iterator it;
for ( it = usermap.begin(); it != usermap.end(); it++ )
{
myfile2 << "Object:" << it->second << "\n";
}

But the error I am getting when I am trying to run the code is - 但是,当我尝试运行代码时遇到的错误是-

In file included from /usr/include/c++/4.8.2/iostream:39:0, from a3part2_5.cpp:2: /usr/include/c++/4.8.2/ostream:548:5: note: template std::basic_ostream& std::operator<<(std::basic_ostream&, const unsigned char*) operator<<(basic_ostream& __out, const unsigned char* __s) ^ /usr/include/c++/4.8.2/ostream:548:5: note: template argument deduction/substitution failed: a3part2_5.cpp:90:31: note: cannot convert 'it.std::_Rb_tree_iterator<_Tp>::operator->, User> >()->std::pair, User>::second' (type 'User') to type 'const unsigned char*' myfile2 << "Obejct: " << it->second << "\\n"; 在/usr/include/c++/4.8.2/iostream:39:0包含的文件中,来自a3part2_5.cpp:2:/usr/include/c++/4.8.2/ostream:548:5:注意:模板std: :basic_ostream&std :: operator <<(std :: basic_ostream&,const unsigned char *)运算符<<(basic_ostream&__out,const unsigned char * __s)^ /usr/include/c++/4.8.2/ostream:548:5:注意:模板参数推导/替换失败:a3part2_5.cpp:90:31:注意:无法转换'it.std :: _ Rb_tree_iterator <_Tp> :: operator->,User>>()-> std :: pair,User > :: second'(类型'User')键入'const unsigned char *'myfile2 <<“对象:” << it-> second <<“ \\ n”;

Any solutions for resolving the error? 有解决错误的解决方案吗?

My User class is defined as - 我的User类定义为-

class User 
{ 
public: 
string userid; string uid; string gid; string gecos; string directory; string shell; 
User() {} 
};

User is user-defined class and hence ostream cannot understand your User objects when you do myfile2 << "Object:" << it->second << "\\n"; User是用户定义的类,因此当您执行myfile2 << "Object:" << it->second << "\\n"; ostream无法理解您的User对象myfile2 << "Object:" << it->second << "\\n";

This should help Overloading the << Operator for Your Own Classes. 这应该有助于为自己的类重载<<操作符。

So you should overload operator << for your class. 因此,您应该为类重载operator <<

An example: 一个例子:

ostream& operator << (ostream &os, User const& u){
    os << "userid:\t" u.userid << "\n";
    // ...
    return os;
}

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

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