【发布时间】:2013-06-13 04:06:37
【问题描述】:
我想我可以像这样创建和填充 C++ 映射:
39 int main(){
40
41 cout << "Approximate travelling salesman path finder." << endl;
42 cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl << endl;
43
44 map<City, OtherCities> database;
45 ReadInData(&database);
46 ...
47 }
作为旁注,ReadInData 函数只是将map<City, OtherCities> 引用作为参数,其中City 只是字符串的类型定义(城市名称),OtherCities 是优先级队列包含 (string, int) 对,表示其他城市及其与第一个城市的距离。
无论如何,尝试编译它会导致以下错误:
pr3.cpp: In function ‘int main()’:
pr3.cpp:45: error: invalid initialization of non-const reference of type ‘std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::priority_queue<OtherCity, std::vector<OtherCity, std::allocator<OtherCity> >, std::greater<OtherCity> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::priority_queue<OtherCity, std::vector<OtherCity, std::allocator<OtherCity> >, std::greater<OtherCity> > > > >&’ from a temporary of type ‘std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::priority_queue<OtherCity, std::vector<OtherCity, std::allocator<OtherCity> >, std::greater<OtherCity> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::priority_queue<OtherCity, std::vector<OtherCity, std::allocator<OtherCity> >, std::greater<OtherCity> > > > >*’
我在这里做错了什么,并且(除了使用禁忌全局变量之外),还有另一种好方法可以将 database 保留在主函数中并在其他地方填充/使用它吗?我不想只是按值传递它的副本......
【问题讨论】:
-
database不是一个未初始化的变量。假设map指的是std::map,它有一个默认构造函数,database是默认构造的。 -
@K-ballo:已编辑。感谢您指出了这一点! :-)
标签: c++ reference initialization constants pass-by-reference