作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试转换 std::vector<std::string>
到以 NULL 结尾的 C 风格字符串数组 ( char *
)。是否可以不使用 new
进行复制/malloc
?
基本上,我想在没有 new/malloc 的情况下将 vec 转换回与 arr 完全相同的东西。
#include <string>
#include <vector>
#include <stdio.h>
using namespace std;
void print(const char **strs)
{
const char **ptr = strs;
while(*ptr) {
printf("%s ", *ptr);
++ptr;
}
}
void print(std::vector<std::string> &strs) {
for(auto iter = strs.begin(); iter != strs.end(); ++iter) {
printf("%s ", iter->c_str());
}
}
void main()
{
const char *arr[] = { "a", "b", "c", "d", "e", "f", NULL };
vector<string> vec;
const char **str = arr;
while(*str) {
vec.push_back(*str);
++str;
}
vec.push_back((char *) NULL); //Doesn't work
//print(vec);
print((const char **) &vec[0]);
}
最佳答案
仅仅通过设置指向该 vector 开头的指针是不可能的,因为vector<string>
不是您期望的连续字符。
addr1 addr2 addr3
^ ^ ^
| | |
+--------+--------+--------+----
| | | | | | |
| std:: | std:: | std:: |
+----> | string | string | string | ...
| | | | |
| +--------+--------+--------+----
|
|
|
vector<string>
addr1
, addr2
和 addr3
是内存中的随机地址。
因此,解决方案是遍历项目,读取字符串和字符并将它们放入您的 continues 数组中。
关于c++ - 如何将 vector<string> 转换为 null 终止的 char **?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16108062/
我是一名优秀的程序员,十分优秀!