我有一個unsigned char* c
包含元素0x1c。我如何將它添加到std::vector<unsigned char>vect
?我正在使用C++。字符串和字符元素
std::vector<unsigned char>vect; //the vect dimention is dynamic
std::string at="0x1c";
c=(unsigned char*)(at.c_str());
vect[1]=c //error? why?
我有一個unsigned char* c
包含元素0x1c。我如何將它添加到std::vector<unsigned char>vect
?我正在使用C++。字符串和字符元素
std::vector<unsigned char>vect; //the vect dimention is dynamic
std::string at="0x1c";
c=(unsigned char*)(at.c_str());
vect[1]=c //error? why?
你有一個字符串中的一個字符的十六進制表示,你想要的字符?
最簡單的:
unsigned char c;
istringstream str(at);
str >> hex >> c; // force the stream to read in as hex
vect.push_back(c);
(我認爲這應該工作,沒有測試過)
我只是再次重讀你的問題,這條線:
I have an unsigned char* c that contains the element 0x1c
不這意味着實際上你的unsigned char *看起來像這樣:
unsigned char c[] = {0x1c}; // i.e. contains 1 byte at position 0 with the value 0x1c?
以上我的假設......
打印矢量出來cout
,使用一個簡單的for循環,或如果你感覺勇敢
std::cout << std::ios_base::hex;
std::copy(vect.begin(), vect.end(), std::ostream_iterator<unsigned char>(std::cout, " "));
std::cout << std::endl;
這將打印向量中由空格分隔的每個unsigned char
值的十六進制表示。
c是unsigned char*
。 vect是std::vector<unsigned char>
,所以它包含無符號的char值。作業將失敗,因爲operator []
在std::vector<unsigned char>
預計unsigned char
,而不是unsigned char *
。
//The vect dimension is dynamic ONLY if you call push_back
std::vector <std::string> vect;
std::string at="0x1c";
vect.push_back(at);
如果您使用的是C++,請使用std :: string。上面的代碼會將你的「0x1c」字符串複製到向量中。
如果你嘗試做
vect[0] = c;
如果不先用
vect.resize(1);
拓展載體,你會得到分段錯誤,因爲操作符[]不動態擴展矢量。矢量的初始大小是0 btw。
UPDATE:根據OP的評論,這裏就是他所希望的:複製一個無符號字符*到一個std ::向量(iecopying C數組到C++向量)
std::string at = "0x1c";
unsigned char * c = (unsigned char*)(at.c_str());
int string_size = at.size();
std::vector <unsigned char> vect;
// Option 1: Resize the vector before hand and then copy
vect.resize(string_size);
std::copy(c, c+string_size, vect.begin());
// Option 2: You can also do assign
vect.assign(c, c+string_size);
我會說錯誤是因爲vect [1]是一個無符號字符,而c是一個指針。也許`vect [1] = * c`?儘管如此,我還沒有用過C++。 – Tesserex 2011-01-19 15:11:43
注意:如果要設置第一個值,您可能需要`vect [0]`而不是`vect [1]`。另外,你真的得到了什麼錯誤? – Maxpm 2011-01-19 15:12:43
我有分段錯誤:( – elisa 2011-01-19 15:15:11