关于 set::insert 的一个问题,在 VC++ 2003 下编译通过,在 Dev-C++ 中编译报错

fatalerror99 2004-12-21 11:59:10
这是一本书中的标准答案,而且在 VC++ 2003 下编译通过,但是在 Dev-C++ 中却编译报错,麻烦大家帮忙看看。

源程序如下:
#include <iostream>
#include <set>
#include <list>
#include <string>
#include <algorithm>
#include <iterator>

int main()
{
using std::string;
using std::cin;
using std::cout;
using std::ostream_iterator;
using std::copy;
using std::pair;

typedef std::set<string> WordSet;
typedef WordSet::iterator WordIter;
typedef std::list<string> Index;

WordSet words;
Index input_order;

for ( string new_word; cin >> new_word, new_word != "Quit"; )
{
pair<WordIter, bool> &trace = words.insert ( new_word );
if ( trace.second )
input_order.push_back ( *trace.first );
}

copy ( input_order.begin(), input_order.end(),
ostream_iterator<string> ( cout, "\n" ) );

copy ( words.begin(), words.end(), ostream_iterator<string> ( cout, "\n" ) );

return 0;
}

错误在这一行:
pair<WordIter, bool> &trace = words.insert ( new_word );

错误信息如下:
Ex05_11.cpp: In function `int main()':
Ex05_11.cpp:26: error: could not convert `std::set<_Key, _Compare,
_Alloc>::insert(const _Key&) [with _Key = std::string, _Compare =
std::less<std::string>, _Alloc = std::allocator<std::string>]((&new_word))'
to `std::pair<std::_Rb_tree_iterator<std::string, const std::string&, const
std::string*>, bool>&'
...全文
280 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
fatalerror99 2004-12-28
  • 打赏
  • 举报
回复
谢谢各位回答,结帖。
fatalerror99 2004-12-26
  • 打赏
  • 举报
回复
楼上说对了,不过那确实是书上的标准答案,而且在 Visual C++ 2003 上能够通过,在 Dev-C++ 下才报错。

但如果说是 Visual C++ 2003 错了好像也不大对,因为我去掉那个 & 以后,在两个编译器上都能通过,而且执行结果与先前 Visual C++ 2003 编译的版本相同。

我曾经想 Visual C++ 2003 调试状态下跟踪看个究竟,但是没有 & 的版本 trace 的赋值过程看得很清楚,加上 & 后却无论如何看不到 trace 的值,结果确实正确的,真是奇哉怪也。

哪位大侠能想办法看到这个有 & 的版本 trace 的赋值过程,感激不尽。

另外,才40多页,已经看出《C++ 程序设计语言题解》里面已经大约3、4个错误了,看来那个叫 David Vandevoorde 的作者功底也不怎么样,不少是比较低级的基础错误,很怀疑他是不是测试过他的程序,这本书……权做参考吧。
fangrk 2004-12-26
  • 打赏
  • 举报
回复
有些编译器比较宽容吧!我对这个跟踪没兴趣。

比如
int* xxx(int i)
{
return &i;
}
这个函数在有些编译器上可能可以得出正确结果,有些编译器上编译通不过。就是各个编译器的不同之处吧!我觉得没必要对这种地方详细研究。呵呵
fatalerror99 2004-12-26
  • 打赏
  • 举报
回复
是呀,楼上说的我已经知道了,而且函数无法返回引用是一件很明显的事情,使我一时眼花,每注意到这个问题。

现在,我是想知道这个错误的程序是怎样得出正确的结果的,为什么在 VC 2003 中编译运行后得到正确的结果。

从跟踪过程看,与没有 & 的版本的执行过程并不一样,但我无法跟踪 trace 的赋值过程,这是一个很怪的问题,不知道 fangrk 有没有兴趣试试。
fangrk 2004-12-26
  • 打赏
  • 举报
回复
只要去看STL的官方文档好了,文档中说返回类型为pair<iterator,bool>,不是pair<iterator,bool>&,其实想想好了,这种函数不可能返回引用的。
yjh1982 2004-12-22
  • 打赏
  • 举报
回复
嗯!的确是vc2003错了.
至少我看的stl书set::insert返回临时对象,而临时对象能赋给常数引用
不能赋给非常数引用
yjh1982 2004-12-22
  • 打赏
  • 举报
回复
fangrk(加把油,伙计!) 说的是.
引用好象不能指向临时对象,是vc2003错了吧
ilovevc 2004-12-22
  • 打赏
  • 举报
回复
看提示好像 Dev-C++ 中的set::insert返回this,而不是pair。奇怪
fangrk 2004-12-22
  • 打赏
  • 举报
回复
pair<WordIter, bool> trace = words.insert ( new_word );

不要用引用

24,855

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧