奇怪裸指针到vector的构造过程
首先,vector的构造有以下几种
default
explicit vector (const allocator_type& alloc = allocator_type());
fill
explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type());
range
template <class InputIterator>
vector (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());
copy
vector (const vector& x);
一般用的是2,填充vector的内容,或者直接不填内容,但是对于一个奇怪类型的指针,也是可以直接拷贝内容到vector的,只需要指定从哪里开始,到哪里结束。比如:
uint8_t* p = (uint8_t*)"1233321";
vector<uint8_t> arr(p, p + sizeof p);
vector到string的转换过程
首先,string的构造过程:
default (1)
string();
copy (2)
string (const string& str);
substring (3)
string (const string& str, size_t pos, size_t len = npos);
from c-string (4)
string (const char* s);
from sequence (5)
string (const char* s, size_t n);
fill (6)
string (size_t n, char c);
range (7)
template <class InputIterator>
string (InputIterator first, InputIterator last);
常用的应该是1,2,4,5,6,少见的是子串拷贝的形式和迭代器的形式
子串拷贝只需要指定从哪里开始,拷贝多长
std::string s0 ("Initial string");
std::string s3 (s0, 8, 3);
//s3: str
std::string s5 ("Another character sequence", 12);
//s5: Another char
std::string s7 (s0.begin(), s0.begin()+7);
//s7: Initial
我们这里要vector拷贝到string里面,就需要用到迭代器了,迭代器形式则不同,是指定从哪里开始,到哪里结束
std::string decode(const std::vector<uint8_t>&in) {
return std::string(in.data(), in.data() + in.size());
}
总结
给个例子
#include <string>
#include <iostream>
#include <vector>
using namespace std;
std::string decode(const std::vector<uint8_t>&in) {
return std::string(in.data(), in.data() + in.size());
}
int main()
{
uint8_t* p = (uint8_t*)"1233321";
vector<uint8_t> arr(p, p + sizeof p);
string str = decode(arr);
cout<<str<<endl;
}
两个顺口溜:
子串拷贝从哪开始拷多长
迭代器式/指针拷贝从哪开始到哪结束