0
Strings in c++?
Why do strings in c++ have array like properties? Edit: https://code.sololearn.com/c4ijn3MBIiP6/?ref=app Take this code for example. The string is treated as an array and I can call a specific index from it.
8 Réponses
+ 6
namespace std {
template<> struct char_traits<char> {
typedef char char_type;
typedef int int_type;
typedef streamoff off_type;
typedef streampos pos_type;
typedef mbstate_t state_type;
static void assign(char_type& c1, const char_type& c2) noexcept;
static constexpr bool eq(char_type c1, char_type c2) noexcept;
static constexpr bool lt(char_type c1, char_type c2) noexcept;
static int compare(const char_type* s1, const char_type* s2, size_t n);
static size_t length(const char_type* s);
static const char_type* find(const char_type* s, size_t n, const char_type& a);
static char_type* move(char_type* s1, const char_type* s2, size_t n);
static char_type* copy(char_type* s1, const char_type* s2, size_t n);
//... Too long to fit
};
}
+ 5
Daniel Cooper There's no such thing like "you're an idiot!" lol
It's true that it finally boils down to its basic building block at the lowest level, but it goes through some different intermediate stages than C.
In C, an string object comprises some mechanism to handle char sequence (array) manipulation. As C11 standard says
" The header <string.h> declares one type and several functions, and defines one macro useful for manipulating arrays of character type [...]"
In C++ however, string library's implementation is like a beast with 3 heads!
These 3 components of the string library are
1. Character traits: which is implemented by class templates using CharT -- CharT is a character container -- , char, char16_t, char32_t, and wchar_t. For example the following list shows one of the declarations.
...
+ 5
2. String (basic_string): which is pretty much the same as char_traits but for manipulating varying-length sequences of char-like objects. It has four typedefs, string, u16string, u32string, and wstring.
3. Null-terminated sequence utilities (for backward compatibility): Which comprises <cctype>, <cwctype>, <cstring>, <cwchar>, <cstdlib>
(character conversions), and <cuchar> header files. The content of these headers conform the C standard library.
+ 4
C++ Soldier (Babak) You have right 😂😂😂... I remember when tried to see the string header source. This was my expression 😕 followed, in order by 😱 😡 😤 😭
+ 4
KrOW LOL ;D
I told it's a beast!
Being implemented with templates make it even harder to read.
But for the sake of argument, It provides some good overall example of the two languages differences behind the scene.
+ 2
C++ Soldier (Babak) Yes, its good from an understanding point of view, but its MUCH BETTER to be armed with VERY GOOD knowldgments of template else would be like try to read arab by knowing only english 😁
+ 1
That was much simpler than I was expecting xD
And it makes sense.
I am probably just an idiot xD
0
Because a string is an array of char