C++ 使用std::vector::begin vs begin(vector)
如果我有C++ 使用std::vector::begin vs begin(vector),c++,c++11,vector,C++,C++11,Vector,如果我有std::vector(它是std::vector,并且将始终是std::vector) 使用std::begin()而不是std::vector::begin()(或相反)是否更优越 性能是否会有任何提高/降低 示例: std::vector<int> foo(100, 5); std::sort(foo.begin(), foo.end()); // Case 1 std::sort(std:begin(foo), std::end(foo)); // Ca
std::vector
(它是std::vector
,并且将始终是std::vector
)
使用std::begin()
而不是std::vector::begin()
(或相反)是否更优越
性能是否会有任何提高/降低
示例:
std::vector<int> foo(100, 5);
std::sort(foo.begin(), foo.end()); // Case 1
std::sort(std:begin(foo), std::end(foo)); // Case 2
标准:向量foo(100,5);
排序(foo.begin(),foo.end());//案例1
std::sort(std:begin(foo),std::end(foo));//案例2
对于“普通”std
-集装箱类型std::begin(c)
实际上与c.begin()相同。我的两便士:
(它是一个std::vector,并且将始终是一个std::vector)
依我看,这是你现在不能做出的保证——这是对自由函数形式的论证
使用std::begin()而不是std::vector::begin()是否优于std::vector::begin()
仅在自由函数形式参与ADL的意义上
性能是否会有任何提高/降低
如果启用了Optimizer,则不会启用。的副本。第一个答案似乎回答了你的问题。它的全部内容都是重复的。非成员函数将调用成员函数,它将完全内联。std::begin
也将使用C风格的数组,这就是区别的目的。就风格而言,我的大脑更喜欢对象拥有自己的行为,而不必使用C风格的数组,也就是说。我在发布之前看到了副本。我不认为这与性能有关。@Tartan Undoplicated:为了找到一个副本,您需要找到一个能够解决上述问题的性能部分的答案。谢谢。。。“如果您启用了Optimizer,则不会。”如果您不介意的话,请在这里再深入一点。如果您不启用优化,编译器将生成实际调用std::begin()的代码,而std::vector::begin()又直接调用std::vector::begin()。如果您启用了优化,它将有效地跳过std::begin()调用,直接转到std::vector::begin(),如果它这样做的话。很可能它将直接在调用站点内联std::vector::begin()的核心。@HumamHelfawi Rob在这里的回答是正确的。我将更进一步,因为我已经研究了在clang/libc++和-O2/3下使用std::algorithms和containers的汇编输出。编译器将其归结为基于指针的迭代,创建了几乎完美的代码。@RobK我会同意您的意见,但至少gcc和-O0会为std::vector
:vs生成完全相同的代码