Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::string size() a O(1) operation?

Is std::string size() a O(1) operation?

The implementation of STL I'm using is the one built into VC++

like image 936
Brian R. Bondy Avatar asked Nov 01 '08 20:11

Brian R. Bondy


People also ask

What does std::string () do?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

Does size () work for string C++?

The C++ String class has length() and size() function. These can be used to get the length of a string type object. To get the length of the traditional C like strings, we can use the strlen() function.

What is the size of std::string?

While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation.

What is the size of string in C++?

In C++, string length really represents the number of bytes used to encode the given string. Since one byte in C++ usually maps to one character, this metric mostly means “number of characters,” too.


3 Answers

If you're asking if MSVC's implementation of string::size() has constant complexity, then the answer is yes. But Don Wakefield mentioned Table 65 in 23.1 of the C++ Standard where it says that the complexity of size() should follow what's said in 'Note A'. Note A says:

Those entries marked ‘‘(Note A)’’ should have constant complexity.

However, that does not mean that those entries shall have constant complexity. Standards use very specific terminology, and "should" means that it is not mandatory.

'Note A' was added to the standard specifically to appease those who believed that size() should be allowed to have linear complexity so it would not be necessary to keep the size when the containers were modified.

So you can't rely on size() having constant complexity, but I'm honestly not sure if there are any implementations that do not have a constant string::size().

like image 191
Michael Burr Avatar answered Oct 23 '22 23:10

Michael Burr


Here's an easy way to answer that question for msvc++.

Write some code in a project:

string happy;
happy.size();

Hilight the .size call, right-click, go to definition.

On my install (vs2005sp1) this sends me to xstring:1635, which looks like this:

size_type __CLR_OR_THIS_CALL size() const
    {   // return length of sequence
    return (_Mysize);
    }

So it looks like the string has a member called _Mysize, and it's just returning that.

In other words, this is a O(1) implementation.

like image 41
tfinniga Avatar answered Oct 23 '22 23:10

tfinniga


Yes, std::string::size() is O(1).

like image 8
lacker Avatar answered Oct 23 '22 21:10

lacker