字符串::在 Visual Studio 下交换复杂度 [英] string::swap complexity under Visual Studio

查看:32
本文介绍了字符串::在 Visual Studio 下交换复杂度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

cppreference 页面介绍了 std::basic_string::swap 它具有恒定的复杂性.正如我假设的那样,这意味着不能复制内容,只能交换指针或类似的内容.我写了一个测试代码并体验到它确实在VS2010下移动了内容.测试代码:

The cppreference page says about std::basic_string::swap that it has constant complexity. As I assume that means that copying contents cannot happen, only the swapping of pointers, or similar. I wrote a test code and experienced that it does move contents under VS2010. Test code:

std::string s1("almafa");
std::string s2("kortefa");
std::cout << "s1.c_str(): "<< (void*)s1.c_str() << std::endl;
std::cout << "s2.c_str(): "<< (void*)s2.c_str() << std::endl;
std::cout << "SWAP!" << std::endl;
s1.swap(s2);
std::cout << "s1.c_str(): "<< (void*)s1.c_str() << std::endl;
std::cout << "s2.c_str(): "<< (void*)s2.c_str() << std::endl;

在 g++ 4.6.3 上输出

Output on g++ 4.6.3

s1.c_str(): 0x22fe028
s2.c_str(): 0x22fe058
SWAP!
s1.c_str(): 0x22fe058
s2.c_str(): 0x22fe028

VS2010 输出

s1.c_str(): 000000000022E2D0
s2.c_str(): 000000000022E320
SWAP!
s1.c_str(): 000000000022E2D0
s2.c_str(): 000000000022E320

是与标准有偏差还是发生了我不知道的事情?

Is it a divergency from the standard or something is happening that I have no knowledge about?

推荐答案

std::string 的一些实现使用了短字符串优化:

来自std::string 是如何实现的?:

短字符串优化"(SSO)实现.在这个变体中,对象包含指向数据、长度、动态分配缓冲区大小等的常用指针.但是如果字符串足够短,它将使用该区域来保存字符串,而不是动态分配缓冲区.

a "short string optimization" (SSO) implementation. In this variant, the object contains the usual pointer to data, length, size of the dynamically allocated buffer, etc. But if the string is short enough, it will use that area to hold the string instead of dynamically allocating a buffer.

因此,您的情况下的交换会复制但大小固定,因此 O(1).

So the swap in your case does a copy but of fixed size, so O(1).

这篇关于字符串::在 Visual Studio 下交换复杂度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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