31

を使用して、スペースで区切られた浮動小数点値のリストで構成される文字列を作成するとstd::ostringstream:

std::ostringstream ss;
unsigned int s = floatData.size();
for(unsigned int i=0;i<s;i++)
{
    ss << floatData[i] << " ";
}

次に、結果を次のように取得しますstd::string

std::string textValues(ss.str());

ただし、これにより、文字列コンテンツの不要なディープ コピーが作成され、ss使用されなくなります。

コンテンツ全体をコピーせずに文字列を作成する方法はありますか?

4

6 に答える 6

13

std::ostringstream非移植性をサポートしない限り、メモリ内バッファにアクセスするためのパブリック インターフェイスを提供しませんpubsetbuf(ただし、バッファは固定サイズです。cppreference の例を参照してください) 。

一部の文字列ストリームを拷問したい場合は、保護されたインターフェイスを使用してバッファーにアクセスできます。

#include <iostream>
#include <sstream>
#include <vector>

struct my_stringbuf : std::stringbuf {
    const char* my_str() const { return pbase(); } // pptr might be useful too
};

int main()
{
    std::vector<float> v = {1.1, -3.4, 1/7.0};
    my_stringbuf buf;
    std::ostream ss(&buf);
    for(unsigned int i=0; i < v.size(); ++i)
        ss << v[i] << ' ';
    ss << std::ends;
    std::cout << buf.my_str() << '\n';
}

自動サイズ変更出力ストリーム バッファに直接アクセスする標準的な C++ の方法はstd::ostrstream、C++98 で廃止されましたが、標準の C++14 とカウントによって提供されます。

#include <iostream>
#include <strstream>
#include <vector>

int main()
{
    std::vector<float> v = {1.1, -3.4, 1/7.0};
    std::ostrstream ss;
    for(unsigned int i=0; i < v.size(); ++i)
        ss << v[i] << ' ';
    ss << std::ends;
    const char* buffer = ss.str(); // direct access!
    std::cout << buffer << '\n';
    ss.freeze(false); // abomination
}

ただし、最もクリーンな(そして最速の)ソリューションはboost.karmaだと思います

#include <iostream>
#include <string>
#include <vector>
#include <boost/spirit/include/karma.hpp>
namespace karma = boost::spirit::karma;
int main()
{
    std::vector<float> v = {1.1, -3.4, 1/7.0};
    std::string s;
    karma::generate(back_inserter(s), karma::double_ % ' ', v);
    std::cout << s << '\n'; // here's your string
}
于 2014-10-10T03:42:56.550 に答える