如果這是有效的:分配值::串
unsigned char buffer[] = {
0x01, 0x02, 0x03, 0x04
};
這是否適用於的std :: string爲好,例如
std::string buffer = {
0x01, 0x02, 0x03, 0x04
};
如果不是,我該如何插入這些值?
如果這是有效的:分配值::串
unsigned char buffer[] = {
0x01, 0x02, 0x03, 0x04
};
這是否適用於的std :: string爲好,例如
std::string buffer = {
0x01, 0x02, 0x03, 0x04
};
如果不是,我該如何插入這些值?
不是在C++ 03,但你可以做到這在C++ 011:
std::string buffer = { 0x01, 0x02, 0x03, 0x04 }; //C++011 ONLY
演示:http://www.ideone.com/1cOuX。在演示中,我只是爲了演示而使用可打印的字符('A'
,'B'
等)。
在C++ 03,由於@andrewdski給出的解決方案是公認醜陋,你可以這樣做,而不是:
unsigned char values[] = {0x01, 0x02, 0x03, 0x04 };
std::string buffer(values, values + sizeof(values));
這是一個有點更簡潔的方法。如果你想以後添加更多的價值,那麼你可以這樣做:
unsigned char more_values[] = {0x05, 0x06, 0x07, 0x08 };
buffer.insert(buffer.end(), more_values, more_values+ sizeof(more_values));
,如果你想從其他std::string
增加值,那麼你可以這樣做:
//add values from s to buffer
buffer.insert(buffer.end(), s.begin(), s.end());
這是一樣的:
buffer += s; //cool
順便說一句,你可以令狀EA的小工具,叫做join
能做到這一點,除了其他有趣的事情:
std::string s = join() + 'A' + 'B' + 'C' + 'D';
您可以在一個單一的join
語句,甚至混合不同類型:
std::string s = join() + 'A' + 'B' + 'C' + 'D' + "haha" + 9879078;
這是不可能的{}
方法即使在C++ 011中。
的實用性和它的一個完整的演示如下圖所示:
#include <iostream>
#include <string>
#include <sstream>
struct join
{
std::stringstream ss;
template<typename T>
join & operator+(const T &data)
{
ss << data;
return *this;
}
operator std::string() { return ss.str(); }
};
int main() {
std::string s1 = join() + 'A' + 'B' + 'C' + 'D';
std::cout << s1 << std::endl;
std::string s2 = join() + 'A' + 'B' + 'C' + 'D' + "haha" + 9879078;
std::cout << s2 << std::endl;
}
輸出:
ABCD
ABCDhaha9879078
在線演示:http://www.ideone.com/3Y7pB
然而,這個工具需要與特定鑄造要插入字符串的值爲:
std::string buffer=join()+ (char)0x01 +(char)0x02 + (char)0x03 + (char)0x04;
沒有這麼酷,誠然。需要強制轉換,否則每個值將被視爲您不想要的int
類型。所以我會提倡更清晰的方法。但是該實用程序可以在其他情況下幫助您。有時候,它很好地嘗試使用C++運算符和功能。 :D
std::string buffer = "\x01\x02\x03\x04"
是一種醜陋的,但它的作品。
是的,這是由於存在'std :: string(std :: initializer_list)'構造函數。 –
ephemient
2011-05-19 05:49:38