std::vector から生配列を取り出したい
vector<char>
から char *
を取り出して istream::read
に使うことはできないの? read( (char *)v.first(), v.size() )
とか書けたら便利だと思ったんだけど.
#include <iostream> #include <iomanip> #include <fstream> #include <vector> using namespace std; int main(int argc, char *argv[]) { ifstream ifs(argv[0], ios::binary); vector<char> v(1024); ifs.read((char *)v.begin(), v.size()); // (*) for (vector<char>::const_iterator i(v.begin()); i != v.end(); ++i) { cout << hex << setw(2) << setfill('0') << static_cast<unsigned int>(*i); } cout << endl; return 0; }
(*) のところが
error C2440: '型キャスト' : 'std::_Vector_iterator<_Ty,_Alloc>' から 'char *' に変換できません。
with
[
_Ty=char,
_Alloc=std::allocator<char>
]
この変換を実行可能なユーザー定義変換演算子がないか、または演算子を呼び出せません。
だとか
In function 'int main(int, char**)':
Line 13: error: invalid cast from type '__gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator> >, __gnu_debug_def::vector > >' to type 'char*'
で止まってしまう.
GNU libstdc++だと vector::data
という拡張メンバ関数があるようだが...
// _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. // data access /** * Returns a pointer such that [data(), data() + size()) is a valid * range. For a non-empty %vector, data() == &front(). */ pointer data() { return pointer(this->_M_impl._M_start); }