Whats the difference between string.function() or function(string) in C++?
If we define:
std::string string; string.length(); // is calling the length method/member function of the string object.
On the other hand,
is calling a free function(not a method/member function) defined in the STL algorithm library(http://en.cppreference.com/w/cpp/algorithm/reverse), thus we cannot do
A method should be called on an object. A free function should be called without an object.
By the way,
string is not a primitive type(its a class defined in
<string>). Primitive types(
char…) dont have any methods.
How can I determine when to use which form?
Whatever fits your needs best. Technically there is no downside either using e.g.
std::find. While member functions like
std::string::find might offer easier usage for their container type, they are limited to only this very container type (e.g.
The motivation of the algorithm library (e.g. where
std::reverse belongs to) is to give the user one interface which works with different containers like
std::map etc. This is achieved by using iterators which every container has.