有没有办法在 C++ 中将 std::string 转换为 vector<char> ?

Sam*_*ing 1 c++ type-conversion stdstring stdvector

有没有一种简单的方法可以将 std::string 转换为 std::vector 我想让用户输入任何长度的字符串,然后有一个动态字符数组(向量)。

#include<iostream>
#include<vector>
#include<string>



int main() {
    std::vector<char> word;
    std::string strWord;
    std::getline(std::cin, strWord);
    //What comes next? 
}
Run Code Online (Sandbox Code Playgroud)

我尝试过但不起作用的一件事是: strcpy(word, strWord); 我收到错误消息,没有从“std::string”到“const char*”的合适转换存在。因此,由于“word”是指向 char 数组的指针,我该如何添加字符串?

Mik*_*CAT 7

您可以通过 将字符串中的字符插入到向量中std::vector::insert()

word.insert(word.end(), strWord.begin(), strWord.end());
Run Code Online (Sandbox Code Playgroud)

要做到转换时,构造std::vector是采用了迭代器来复制数据从也很有用。

word = std::vector(strWord.begin(), strWord.end());
Run Code Online (Sandbox Code Playgroud)