1.vector轉string
std::string Str = "hello world!";
std::vector<uint8_t> Vec;
Vec.assign(Str.begin(), Str.end());
2.string轉vector
std::string Str;
std::vector<uint8_t> Vec(6, 7);
Str.assign(Vec.begin(), Vec.end());
#include <iostream> #include <vector> #include <string> using std::string; using std::vector; int main() { vector<unsigned char> Vec1; string Str{"123456"}; Vec1.assign(Str.begin(), Str.end()); std::cout << "String data is: " << std::endl; for(auto aa : Str) printf("%02x ", aa); std::cout << std::endl; std::cout << "Vector data is: " << std::endl; for(auto aa : Vec1) printf("%02x ", aa); std::cout << std::endl; }
3.vector相關操作
Vec.erase(Vec.begin(), Vec.end()) /*刪除所有*/
Vec.erase(Vec.begin())
Vec.clear() /*刪除所有*/
Vec.empty() /*判斷是否為空*/
Vec.capacity() /*返回容器當前已分配的容量*/
Vec.front() /*傳回第一個數據*/
Vec.insert(Vec.begin(), 7) /*在Vec起始位置插入數據7*/
Vec.push_back(8) /*在尾部加入一個數據8*/
Vec.pop_back() /*刪除最后一個數據*/
Vec.size() /*返回容器中實際數據的個數*/
Vec.rbegin() /*傳回一個逆向隊列的第一個數據*/
Vec.rend() /*傳回一個逆向隊列的最后一個數據的下一個位置*/
Vec.resize(num) /*重新指定隊列的長度為num*/
Vec.reserve() /*保留適當的容量*/
Vec1.swap(Vec2) /*將Vec1和Vec2元素互換 swap(Vec1, Vec2) */
4.string與char *
string str = "hello";
const char* p = str.data();
const char *p = str.c_str();
char cp[50];
str.copy(cp, 5, 0); /*5代表復制幾個字符,0代表復制的位置*/
char *chp[str.length() + 1];
strcpy(chp, str.c_str());