这是相当广泛的,所以提前,如果你通过了这个,即使没有答案或解决方案,谢谢。
所以,我有这个程序,它是一个基本的社交网络,减去用户界面,其中用户由 Person
表示对象,它负责维护好友列表、阻止列表、消息列表和待处理好友请求队列。这些列表分别属于 std::map<std::string, Person>
类型, std::map<std::string, Person>
, std::vector<Message>
, 和 std::queue<Message>
, 其中std::string
对于这两个 map ,是用户的名字和姓氏以及 Message
的串联在最后两个容器中是我定义的附加类。我已经重载了 <<
Person
的运算符这样它会打印用户的名字和姓氏,中间有一个空格。出于某种原因,当我去打印这些名字时,返回是空的,我不知道为什么。以下代码本质上是对正在发生的事情的演练。
我用来在主类中测试我的代码的行:
std::string cFirst ("Chris");
std::string cLast ("Cringle");
SocialNetwork sn;
sn.addUser(cFirst,cLast);
addUser()
在 SocialNetwork
中发挥作用:
void SocialNetwork::addUser(std::string first, std::string last){
std::string name = (first + last);
Person user (first, last);
_users.insert(std::pair<std::string, Person>(name, user));
}
在哪里_users
是SocialNetwork
上的成员(member)数据类型 std::map<std::string, Person>
. Person
的构造函数是:
Person::Person(std::string first, std::string last){
_first = first;
_last = last;
}
在哪里_first
和 _last
是 Person
上的成员(member)数据代表用户的名字和姓氏。然后,回到主类(class),在 sn.addUser(cFirst,cLast);
之后:
sn.printUsers();
看起来像:
void SocialNetwork::printUsers(){
std::map<std::string, Person>::iterator it;
it = _users.begin();
while(it != _users.end()){
cout << it->first << endl;
cout << it->second << endl;
it++;
}
}
使用给定的代码,cout << it->first << endl;
的预期输出应该是 ChrisCringle
, 它是。 cout << it->second << endl;
的预期输出应该调用重载运算符并且应该是 Chris Cringle
, 但它只是打印一个空格。任何关于原因的迹象将不胜感激。我需要通过引用传递我的参数吗?我已经尝试过了,但似乎遇到了很多麻烦。如果似乎缺少某些可能有帮助的东西,请随时提出!再次感谢!我知道我可能会因为这个长问题而受到很多批评,但我认为我无法设法让这个问题变得更简单。
编辑:重载运算符的代码是:
ostream& operator<<(ostream& os, const Person& per){
os << per._first << " " << per._last;
return os;
}
最佳答案
我刚刚使用了您显示的所有代码:http://ideone.com/mFBxTC
#include <string>
#include <iostream>
#include <map>
using namespace std;
struct Person {
Person(std::string first, std::string last);
std::string _first, _last;
};
ostream& operator<<(ostream& os, const Person& per){
os << per._first << " " << per._last;
return os;
}
struct SocialNetwork {
void addUser(std::string first, std::string last);
std::map<std::string, Person> _users;
void printUsers();
};
void SocialNetwork::addUser(std::string first, std::string last){
std::string name = (first + last);
Person user (first, last);
_users.insert(std::pair<std::string, Person>(name, user));
}
Person::Person(std::string first, std::string last){
_first = first;
_last = last;
}
void SocialNetwork::printUsers(){
std::map<std::string, Person>::iterator it;
it = _users.begin();
while(it != _users.end()){
cout << it->first << endl;
cout << it->second << endl;
it++;
}
}
int main() {
std::string cFirst ("Chris");
std::string cLast ("Cringle");
SocialNetwork sn;
sn.addUser(cFirst,cLast);
sn.printUsers();
return 0;
}
而且效果很好。所以错误在别处
这就是为什么应该发布 SSCCE在发布调试问题时。
关于c++ - C++ 映射及其内容的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34300613/