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

标签 c++ string iterator char stdvector

如何将 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/

相关文章:

rust - 如何解决预期的 `:` ,发现关键字 `self` ?

c++ - 派生自在私有(private)范围内声明的类

c++ - ssl 对等证书或 ssh 远程 key 不正确 - C

r - 如何将所有转义字符保留在 SQL 字符串中以使用 R 查询 POSTGRES 数据库?

r - 根据列中的字符串拆分表

python - 为什么我的代码 'next()' 函数在这个例子中没有被调用?

c++ - 在 `for` 循环内递增后,迭代器结束检查失败

c++ - `std::array<T, 0>` 是默认构造的,而 `T` 不是默认构造的吗?

C++ 表达式模板不明确的运算符重载

C++ 返回字符串