我需要将整个文件读入内存并将其放在C++中std::string.
如果我把它读成a char[],答案很简单:
std::ifstream t;
int length;
t.open("file.txt"); // open input file
t.seekg(0, std::ios::end); // go to the end
length = t.tellg(); // report location (this is the length)
t.seekg(0, std::ios::beg); // go back to the beginning
buffer = new char[length]; // allocate memory for a buffer of appropriate dimension
t.read(buffer, length); // read the whole file into the buffer
t.close(); // close file handle
// ... Do stuff with buffer here ...
Run Code Online (Sandbox Code Playgroud)
现在,我想做同样的事情,但是使用a std::string而不是a char[] …
string s = "????";
wstring ws = FUNCTION(s, ws);
Run Code Online (Sandbox Code Playgroud)
我如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们无法分配确切的内容.内容失真.
我正在为一段返回大型数组的C代码制作一个C++包装器,所以我试图将数据返回到vector<unsigned char>.
现在问题是,数据大小为兆字节,并且vector不必要地初始化其存储,这实际上是将我的速度降低了一半.
我该如何防止这种情况?
或者,如果不可能 - 是否有其他STL容器可以避免这种不必要的工作?或者我最终必须制作自己的容器?
(预C++ 11)
我将矢量作为输出缓冲区传递.我不是从其他地方复制数据.
它是这样的:
vector<unsigned char> buf(size); // Why initialize??
GetMyDataFromC(&buf[0], buf.size());
Run Code Online (Sandbox Code Playgroud) 我在我的MFC应用程序中使用std :: string,我想将它存储在doc的Serialize()函数中.我不想将它们存储为CString,因为它在那里写了自己的东西,我的目标是创建一个我知道格式的文件,并且可以被其他应用程序读取而不需要CString.所以我想将我的std :: strings存储为4个字节(整数)字符串长度,然后是包含该字符串的大小的缓冲区.
void CMyDoc::Serialize(CArchive& ar)
{
std::string theString;
if (ar.IsStoring())
{
// TODO: add storing code here
int size = theString.size();
ar << size;
ar.Write( theString.c_str(), size );
}
else
{
// TODO: add loading code here
int size = 0;
ar >> size;
char * bfr = new char[ size ];
ar.Read( bfr, size);
theString = bfr;
delete [] bfr;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不是很好,我必须分配一个临时bfr来读取字符串.首先,我可以直接将字符串读入std :: string而不使用临时缓冲区吗?其次我可以重载<<缓冲区为std :: string/CArchive所以我可以简单地使用ar << theString?总的来说有一种更好的方法来使用CArchive对象读/写std :: string吗?
根据这些问题的答案中的陈述
..在C++ 11中应该可以调用一个C API函数,它接受一个char指针来存储输出,如下所示:
str::string str;
str.reserve(SOME_MAX_VALUE);
some_C_API_func(&str[0]);
Run Code Online (Sandbox Code Playgroud)
但是现在有一种合法的方法可以将字符串的大小设置为缓冲区内(空终止的)内容的长度吗?像这样的东西:
str.set_size(strlen(&str[0]));
Run Code Online (Sandbox Code Playgroud)
这是一个非常不美观的滥用,std::string无论如何我听到你说,但我不能char在堆栈上创建一个临时缓冲区,所以我必须在堆中创建一个缓冲区并在之后销毁它(我想避免).
有一个很好的方法来做到这一点?也许不是保留,但事后调整和调用erase()会做到但是它感觉不好整洁..
我分配一个char数组然后我需要将它作为一个字符串返回,但我不想复制这个char数组然后释放它的内存.
char* value = new char[required];
f(name, required, value, NULL); // fill the array
strResult->assign(value, required);
delete [] value;
Run Code Online (Sandbox Code Playgroud)
我不想像上面那样做.我需要将数组放在std字符串容器中.我怎么能这样做?
EDIT1:
我明白我不应该并且字符串不是为此而设计的.MB有人知道char数组的另一个容器实现,我可以用它吗?