在某些代碼int8_t[]中使用型別而不是char[].
int8_t title[256] = {'a', 'e', 'w', 's'};
std::string s(title); // compile error: no corresponding constructor
如何正確安全地std::string從中創建一個?
當我要這樣做時,cout << s;我希望它 print aews,就好像char[]type 已傳遞給建構式一樣。
uj5u.com熱心網友回復:
這個給你
int8_t title[256] = { 'a', 'e', 'w', 's' };
std::string s( reinterpret_cast<char *>( title ) );
std::cout << s << '\n';
或者你也可以使用
std::string s( reinterpret_cast<char *>( title ), 4 );
uj5u.com熱心網友回復:
std::string像其他容器一樣,可以使用一對迭代器來構造。如果可用,此建構式將使用隱式轉換,例如轉換int8_t為char.
int8_t title[256] = {'a', 'e', 'w', 's'};
std::string s(std::begin(title), std::end(title));
請注意,此解決方案將復制整個陣列,包括未使用的位元組。如果陣列通常比它需要的大得多,您可以查找空終止符
int8_t title[256] = {'a', 'e', 'w', 's'};
auto end = std::find(std::begin(title), std::end(title), '\0');
std::string s(std::begin(title), end);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364607.html
上一篇:元編程-類冪函式
