简体   繁体   English

boost :: shared_array <char> 到std :: string

[英]boost::shared_array<char> to std::string

What is the best way to convert a boost::shared_array<char> to a std::string ? boost::shared_array<char>转换为std::string的最佳方法是什么? The following snippet works but it does not look very elegant. 以下代码片段有效,但看起来并不优雅。

boost::shared_array<char> boostString = DatabaseFileName.GetCString(CZString::eAscii);
std::string stdString;
for(size_t i = 0; boostString[i] != 0; i++)
{
    stdString.append(1, boostString[i]);    
}

Boost shared array uses new[] to allocate its data, which means it's all contiguous in memory. Boost共享数组使用new[]分配其数据,这意味着它们在内存中都是连续的。 That means you can get a pointer to the first element as a C-style string, from which you can create a std::string instance. 这意味着您可以获取一个指向第一个元素的C风格字符串的指针,从中可以创建一个std::string实例。

This of course requires the data to either have a terminator, or for you to know the length of the "string". 当然,这需要数据具有终结符,或者让您知道“字符串”的长度。

Checkout following code. 签出以下代码。 This will give you clear idea: 这将给您清楚的主意:

#include <iostream>
#include <string>
#include <boost\shared_array.hpp>

void main()
{   
    char *ptr = "mystring" ;
    boost::shared_array<char> myIntArray(new char[strlen(ptr) + 1]);
    strncpy(myIntArray.get(), ptr, strlen(ptr) + 1);
    std::string str(myIntArray.get());
    std::cout << str << std::endl;

    system("pause");
}

If you don't want to futz around with strncpy and worrying of the boost::shared_array<char> is null-terminated, you can write (assuming boostString and stdString from the original example: 如果您不想使用strncpy来解决问题,而担心boost::shared_array<char>是以空boost::shared_array<char>结尾的,则可以编写(假设原始示例中的boostStringstdString为:

std::copy(boostString.begin(), boostString.end(),
    std::back_inserter<std::string>(stdString));

According to "Some Programmer dude"'s answer I coded the solution. 根据“ Some Programmer dude”的回答,我对解决方案进行了编码。 Please notice that the boostString string is zero-terminated. 请注意, boostString字符串以零结尾。

boost::shared_array<char> boostString = str.GetCString(CZString::eAscii);
std::string stdStr(boostString.get());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM