Does C++ have a free function `size(object)`?(C++ 有免费的函数`size(object)`吗?)
问题描述
似乎大多数人找到 string
大小的方式是他们只使用 my_string.size()
并且它工作正常.嗯,我最近为我做过的班级做了一个作业...
It seems that the way that most people find the size of a string
is they just use the my_string.size()
and it works fine. Well, I recently did an assignment for class where I did...
if (size(my_string) < 5)
store[counter].setWeight(stoi(my_string));
而不是......
if (my_string.size() < 5)
store[counter].setWeight(stoi(my_string));
但令我惊讶的是,我认为正在运行旧编译器的讲师无法运行该行代码.在我的编译器上,它是双向的,我不太确定为什么.
But to my suprise my instructor, who I believe is running an older compiler, wasn't able to run that line of code. On my compiler it works both ways and I'm not quite sure why.
一个完整的程序(两者都输出 4):
A complete program (it outputs 4 for both):
#include <string>
#include <iostream>
using namespace std;
int main()
{
string myvar = "1000";
cout << "Using size(myvar) = " << size(myvar) << endl;
cout << "Using myvar.size() = " << myvar.size() << endl;
}
如果有人能解释为什么我的问题解决方案适用于我的机器而不适用于我的教授?另外,我目前正在运行 VS2015.
If anyone can shed some light on why my solution to the problem worked on my Machine but not my Professors? Also, I'm currently running VS2015.
推荐答案
MSVS 2015 在 xutility 中定义了一个 size
函数
MSVS 2015 has a size
function defined in xutility
template<class _Container>
auto inline size(const _Container& _Cont)
-> decltype(_Cont.size())
{ // get size() for container
return (_Cont.size());
}
这是调用时正在使用的函数
This is the function that is being used when you call
cout << "Using size(myvar) = " << size(myvar) << endl;
这不是标准的 C++11/14 函数,不会在 gcc 上运行a> 或 clang
This is not a standard C++11/14 function and will not run on gcc or clang
这在博客文章 VS 2015 RTM 中的 C++11/14/17 特性
这篇关于C++ 有免费的函数`size(object)`吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 有免费的函数`size(object)`吗?


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09