C++ 使用vector<char>初始化string 两种方法

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

using namespace std;

int main() {
    // 使用vector构造函数初始化string
    vector<char> charVec = {'h', 'e', 'l', 'l', 'o'};
    string str(charVec.begin(), charVec.end());
    cout << str << endl; // 输出: hello
    
    // 使用assign函数初始化string
    vector<char> charVec2 = {'w', 'o', 'r', 'l', 'd'};
    string str2;
    str2.assign(charVec2.begin(), charVec2.end());
    cout << str2 << endl; // 输出: world
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43739821/article/details/130085254