C++ 如何使用随机_洗牌与CString?

C++ 如何使用随机_洗牌与CString?,c++,cstring,stdstring,C++,Cstring,Stdstring,我想洗牌CString Variable中的角色。我该怎么做? Std提供一个名为random_shuffle()的finction,可用于按以下方式洗牌Std::string std::字符串s(“ThisIsSample”); 随机洗牌(s.first(),s.last()); 但是由于CString没有访问要迭代的第一个和最后一个字符的函数。如何将随机随机洗牌与CString一起使用?将CString转换为std::string:- CString cs("Hello"); std::st

我想洗牌CString Variable中的角色。我该怎么做? Std提供一个名为random_shuffle()的finction,可用于按以下方式洗牌Std::string std::字符串s(“ThisIsSample”); 随机洗牌(s.first(),s.last());
但是由于CString没有访问要迭代的第一个和最后一个字符的函数。如何将随机随机洗牌与CString一起使用?

将CString转换为std::string:-

CString cs("Hello");
std::string s((LPCTSTR)cs);

NOTE:- BUT: std::string cannot always construct from a LPCTSTR. i.e. the code 
will fail for UNICODE   builds.
编辑以回应评论

由于std::string只能从LPSTR/LPCSTR构造,因此使用VC++7.x或更高版本的程序员可以使用转换类(如CT2CA)作为中介

CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);
在s上使用随机_洗牌,然后:-

CString cs1(s.c_str());
用于获取字符缓冲区,并将其边界传递给
std::random\u shuffle

void shuffle_cstring(CString& c)
{
    size_t len = c.GetLength();
    LPTSTR buf = c.GetBuffer(1);
    std::random_shuffle(buf, buf + len);
    c.ReleaseBuffer();
}

完成操作后需要调用。哦,还应该首先调用
GetLength
,并将结果存储在单独的变量中。因为在调用
GetBuffer
和调用
ReleaseBuffer
@BenjaminLindley之间,您不应该调用
CString
上的任何其他成员函数,我想知道在这种情况下是否真的需要这样做。MSDN表示,如果使用
GetBuffer
返回的指针更改字符串内容,则必须在使用任何其他CString成员函数之前调用
ReleaseBuffer
。代码确实会更改内容,但只能通过重新排列字符来更改,因此它既不会影响字符串的长度,也不会影响当前的字符。交换是3个赋值(1个赋值给外部字符,2个赋值给数组中的元素)。一个任务就是改变一个角色。因此,洗牌正在改变内容。你也许可以侥幸逃脱,但我不明白为什么你会不必要地破坏API的契约,因为你知道以后实现可能会改变,可能会破坏你的代码。@BenjaminLindley我同意
std::random\u shuffle
正在改变缓冲区内容。然而,很值得怀疑的是,角色洗牌会以任何方式影响
GetLength
,特别是当缓冲区保持不变时,需要使用
GetLength
。请注意,您可以使用
std::basic_string
在窄版本中有效地获取
std::string
,在Unicode版本中有效地获取
std::wstring