Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

visual studio 2015 - Does C++ have a free function `size(object)`?

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));

Instead of....

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.

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;
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

size is actually C++17 functionality. The real benefit to is akin to the benefit of begin and end from C++11.

Note that the first definition of size simply returns the container's size method.

So if I have a templated function like this:

template <typename T>
auto foo(const T& bar) { return bar.size(); }

This could only be used with containers, but if I change that to:

template <typename T>
auto foo(const T& bar) { return size(bar); }

It can be used with C-style arrays too. I've added a live example here: http://melpon.org/wandbox/permlink/Rlpi5wueA14JOW2P

In summary, you should always use size and other range based functions because of the improvements to generality and container agnostic code (see here for more).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...