问题描述
似乎大多数人找到 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)`吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!