std :: string和std :: u16string(或u32string)之间的区别 [英] Difference between std::string and std::u16string (or u32string)

查看:4087
本文介绍了std :: string和std :: u16string(或u32string)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面提到以下帖子:

I have referred below posts before asking here:

std :: string,wstring,u16 / 32string澄清

std :: u16string,std :: u32string,std :: string,length(),size(),codepoints and characters

但他们不是我的问题。看看下面的简单代码:

But they don't my question. Look at the simple code below:

#include<iostream>
#include<string>
using namespace std;

int main ()
{
  char16_t x[] = { 'a', 'b', 'c', 0 };
  u16string arr = x;

  cout << "arr.length = " << arr.length() << endl;
  for(auto i : arr)
    cout << i << "\n";
}

输出为:

arr.length = 3  // a + b + c
97
98
99

因此, std :: u16string 包含 char16_t 而不是 char 不应该输出:

Given that, std::u16string consists of char16_t and not char shouldn't the output be:

arr.length = 2  // ab + c(\0)
<combining 'a' and 'b'>
99

请原谅我的新手问题。我的要求是清楚新的C ++ 11字符串的概念。

Please excuse me for the novice question. My requirement is to get clear about the concept of new C++11 strings.

编辑

从@ Jonathan的回答,我有我的问题的漏洞。我的观点是如何初始化 char16_t ,以使 arr 的长度变为 2 (即 ab c\0 )。

FYI,下面给出了不同的结果:

From @Jonathan's answer, I have got the loophole in my question. My point is that how to initialize the char16_t, so that the length of the arr becomes 2 (i.e. ab, c\0).
FYI, below gives a different result:

  char x[] = { 'a', 'b', 'c', 0 };
  u16string arr = (char16_t*)x;  // probably undefined behavior

输出:

arr.length = 3
25185
99
32767


推荐答案

不,你创建了一个包含四个元素的数组,第一个元素是'a'转换为 char16_t ,第二个是'b'转换为 char16_t 等。

No, you have created an array of four elements, the first element is 'a' converted to char16_t, the second is 'b' converted to char16_t etc.

然后,从该数组创建一个 u16string (转换为指针)元素到null终止符。

Then you create a u16string from that array (converted to a pointer), which reads each element up to the null terminator.

这篇关于std :: string和std :: u16string(或u32string)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆