【问题标题】:inserting a double and a pair in map and printing the map [duplicate]在地图中插入双精度和一对并打印地图[重复]
【发布时间】:2021-12-16 01:19:42
【问题描述】:

我想为分数构建一个容器。键将代表双精度分数的值;分子和分母成对存储。

std::map<double, pair<int, int>> m ();

我在插入和打印元素时遇到了问题。您能告诉我如何针对这种特定情况执行此操作吗?

我试过了:

m.insert(make_pair(x/y, make_pair(x, y)));
给我错误

在“m”中请求成员“insert”,它是非类类型 ‘std::map<double, std::pair<int, int> >()’ m.insert(make_pair(x/y, make_pair(x, y)));

for ( auto it1 = m.begin(); it1!=m.end(); ++it1) cout << it1->first << "->" << it1->second << endl; 给了

在‘m’中请求成员‘begin’,非类类型‘std::map<double, std::pair<int, int> >()’ for ( auto it1 = m.begin(); it1!=m.end(); ++it1)

以及 geeksforgeeks 和 SO 上显示的许多其他方式给了我同样的错误,但我不知道为什么。

【问题讨论】:

  • 您在错误的地方寻找问题。 std::map<double, pair<int, int>> m (); 声明了一个函数 m,它不接受任何参数并返回一个 std::map<double, pair<int, int>> - 即编译器告诉你它具有的函数类型。删除()。 (如果您愿意,可以使用{}。)

标签: c++ dictionary printing insert std-pair


【解决方案1】:

你的问题在于 molbdino 所说的:

std::map<double, pair<int, int>>  m ();   

编译器认为它是一个函数名m,没有参数,并返回一个std::map&lt;double, pair&lt;int, int&gt;&gt;,这不是你想要的。

所以,删除()

另一件事是xintyint,所以x / y 是一个整数除法,将返回一个int。但是您的地图需要double

所以你应该把它转换成double

【讨论】:

  • 最初它是std::map&lt;double, pair&lt;int, int&gt;&gt;,但它在程序的其他部分给了我分段错误,我正在使用 stringstream 和我创建的函数将 x 从字符串格式转换为 int 格式。我认为问题在于地图尚未初始化,但是当我将 () 替换为 {} 时,我也会遇到分段错误。可能是功能有问题,但是我用过很多次都没有问题
  • 函数:void tokenize(string const&amp; str, const char delim, vector&lt;string&gt;&amp; out) { stringstream ss(str); string s; while (getline(ss, s, delim)) { out.push_back(s); } } in main:`字符串容器; getline(cin,容器);向量 输出; const char delim = ' ';标记化(容器,分隔符,出); std::map> m {}; for(int i = 0; i > x; }
  • 程序以信号 SIGSEGV 终止,分段错误。 #0 std::__cxx11::basic_stringbuf, std::allocator >::basic_stringbuf (__mode=24, __str=..., this=0x7ffc91fd7748) at /usr/ local/include/c++/8.3.0/ext/new_allocator.h:81 81 new_allocator(const new_allocator&) _GLIBCXX_USE_NOEXCEPT { }
  • @Simona 你应该就你出现的问题提出一个新问题。
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 1970-01-01
  • 2015-10-05
  • 1970-01-01
  • 2019-12-13
  • 2014-07-26
相关资源
最近更新 更多