[英]Is it possible to copy wchar_t* strings to vector as a new string of characters?
What I am trying to do is to save multiple different pointers to unique wchar_t
strings into a vector.我想要做的是将多个不同的指向唯一
wchar_t
字符串的指针保存到一个向量中。 My current code is this:我目前的代码是这样的:
std::vector<wchar_t*> vectorOfStrings;
wchar_t* bufferForStrings;
for (i = 0, i > some_source.length; i++) {
// copy some string to the buffer...
vectorOfStrings.push_back(bufferForStrings);
}
This results in bufferForStrings
being added to the vector again and again, which is not what I want.这导致
bufferForStrings
一次又一次地添加到向量中,这不是我想要的。
RESULT:
[0]: (pointer to buffer)
[1]: (pointer to buffer)
...
What I want is this:我想要的是这样的:
[0]: (pointer to unique string)
[1]: (pointer to other unique string)
...
From what I know about this type of string, the pointer points to the beginning of an array of characters which ends in a null terminator.根据我对这种类型字符串的了解,指针指向以 null 终止符结尾的字符数组的开头。
So, the current code effectively results in the same string being copied to the buffer again and again.因此,当前代码有效地导致相同的字符串一次又一次地复制到缓冲区。 How do I fix this?
我该如何解决?
The simplest way is to use std:wstring
, provided by the STL, as the type for your vector's elements.最简单的方法是使用由 STL 提供的
std:wstring
作为向量元素的类型。 You can use the constructor that class provides to implicitly copy the contents of your wchar_t*
-pointed buffer to the vector (in the push_back()
call).您可以使用 class 提供的构造函数将指向
wchar_t*
的缓冲区的内容隐式复制到向量(在push_back()
调用中)。
Here's a short demo:这是一个简短的演示:
#include <string>
#include <vector>
#include <iostream>
int main()
{
wchar_t test[][8] = { L"first", L"second", L"third", L"fourth" };
std::vector<std::wstring> vectorOfStrings;
wchar_t* bufferForStrings;
size_t i, length = 4;
for (i = 0; i < length; i++) {
// copy some string to the buffer...
bufferForStrings = test[i];
vectorOfStrings.push_back(bufferForStrings);
}
for (auto s : vectorOfStrings) {
std::wcout << s << std::endl;
}
return 0;
}
Further, if you later need access to the vector's elements as wchar_t*
pointers, you can use each element's c_str()
member function to retrieve such a pointer (though that will be const
qualified).此外,如果您以后需要以
wchar_t*
指针的形式访问向量的元素,则可以使用每个元素的c_str()
成员 function 来检索这样的指针(尽管这将是const
限定的)。
There are other methods, if you want to avoid using the std::wstring
class;还有其他方法,如果你想避免使用
std::wstring
class; for 'ordinary' char*
buffers, you could use the strdup()
function to create a copy of the current buffer, and send that to push_back()
.对于“普通”
char*
缓冲区,您可以使用strdup()
function创建当前缓冲区的副本,并将其发送到push_back()
。 Unfortunately, the equivalent wcsdup()
function is not (yet) part of the standard library (though Microsoft and others have implemented it).不幸的是,等效的
wcsdup()
function 还不是标准库的一部分(尽管微软和其他人已经实现了它)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.