gpt4 book ai didi

c++ - 将 vector 转换为 const char* 和 string

转载 作者:行者123 更新时间:2023-11-30 05:28:39 26 4
gpt4 key购买 nike

如何将 vector 转换为 const char* ?还要串?这合法吗?

void Printer::Wrap(const CharVector& text, RangeVector& result) const
//if (TestLineWidth(text.begin(), text.end()))
int c = 0;
for (CharVector::const_iterator it = text.begin(); it != text.end(); ++it)
c++;
if (TestLineWidth(&text[0], &text[c]))

这里是 CharVector 和 TestLineWidth 的声明:

typedef std::vector<char> CharVector;

bool TestLineWidth(const char* from, const char* to) const;

最佳答案

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
vector<char> data = {'h', 'e', 'l', 'l', 'o', '!'};
cout << string(begin(data), end(data)) << endl;
return 0;
}

对于 const char *,你不能只调用 data.data(),因为 C 字符串以 null 结尾,所以你必须在末尾附加 '\0'

关于c++ - 将 vector<char> 转换为 const char* 和 string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36718514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com