C++ 有免费的函数`size(object)`吗?

2023-09-27C/C++开发问题
2

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6