请教vector中的begin()的返回值

Dic4000 2006-08-08 09:13:42
有一程序片段:
vector<int> n;
for(int i=1;i<=100;i++) n.push_back(i);

请问:
1:n.beging()和n.end()的返回值是什么类型?
2:为什么用cout<<n.begin();语句出错?怎样才能打印出n.begin()的值?
...全文
1393 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Torrice 2006-08-08
  • 打赏
  • 举报
回复
看看 STL
云梦谭 2006-08-08
  • 打赏
  • 举报
回复 1
1:n.beging()和n.end()的返回值是什么类型?
返回迭代器,注意end()返回的并不是存储最后一个元素的迭代器,而是存储最后元素迭代器的后一个,也就是说end()-1才是最后一个元素所在迭代器
2:为什么用cout<<n.begin();语句出错?怎样才能打印出n.begin()的值?
在这情况下用cout << *(n.begin());就可以了,迭代器的使用和指针很相似
jixingzhong 2006-08-08
  • 打赏
  • 举报
回复
返回的都是 迭代器(你可以理解为指针),
输出的应当是 迭代器 指向的内容:

*n.begin() *n.end()
jixingzhong 2006-08-08
  • 打赏
  • 举报
回复
#include <vector>
iterator end();
const_iterator end() const;

The end() function returns an iterator just past the end of the vector.

Note that before you can access the last element of the vector using an iterator that you get from a call to end(), you'll have to decrement the iterator first. This is because end() doesn't point to the end of the vector; it points just past the end of the vector.

jixingzhong 2006-08-08
  • 打赏
  • 举报
回复
begin
Syntax:
#include <vector>
iterator begin();
const_iterator begin() const;

The function begin() returns an iterator to the first element of the vector. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

// Create a list of characters
list<char> charList;
for( int i=0; i < 10; i++ ) {
charList.push_front( i + 65 );
}
// Display the list
list<char>::iterator theIterator;
for( theIterator = charList.begin(); theIterator != charList.end(); theIterator++ ) {
cout << *theIterator;
}

Related topics:
end
rbegin
rend
benh 2006-08-08
  • 打赏
  • 举报
回复
1 vector<int>::iterator 类型。
2 *n.begin();
晨星 2006-08-08
  • 打赏
  • 举报
回复
(1)只能告诉你返回vector<int>::iterator类型,而这个类型的具体定义,可能随不同的库实现而不同;

(2)打印一个iterator干嘛啊?你是不是想打印:*n.begin()啊?

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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