vector :: begin()和std :: begin() [英] Difference between vector::begin() and std::begin()

查看:606
本文介绍了vector :: begin()和std :: begin()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++中迭代一个向量,我注意到在标准库中有一个 begin()函数,还有一个 begin 作为向量类的成员函数。

While iterating over a vector in c++, I noticed there is a begin() function in the standard library, and also a begin() as a member function of the vector class. What, if any, is the difference between the two, and which should be used over the other?

例如:

vector<int> numbers;
//Code to put values in my vector
for (vector<int>::iterator i = numbers.begin(); i < numbers.end(); i++)
    cout << *i << '\n';

vs:

vector<int> numbers;
//Code to put values in my vector
for (vector<int>::iterator i = std::begin(numbers); i < std::end(numbers); i++)
    cout << *i << '\n';


推荐答案

std :: begin )在C ++ 11中添加,以便更容易编写通用代码(例如在模板中)。最明显的原因是,简单的C风格数组没有方法,因此没有 .begin()。所以你可以用C型数组使用 std :: begin(),以及有自己的 begin() end()

std::begin() was added in C++11 to make it easier to write generic code (e.g. in templates). The most obvious reason for it is that plain C-style arrays do not have methods, hence no .begin(). So you can use std::begin() with C-style arrays, as well as STL-style containers having their own begin() and end().

如果你编写的代码不是模板,你可以忽略 std :: begin();你的同事程序员可能会发现奇怪,如果你突然开始使用它,无处不在只是因为它是新的。

If you're writing code which is not a template, you can ignore std::begin(); your fellow programmers would probably find it odd if you suddenly started using it everywhere just because it's new.

这篇关于vector :: begin()和std :: begin()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆