开发者

How to store ints into std::vector<int> in c++?

"Working in C++"

I have a UnicodeString that contains some comma seperated integer values e.g: UnicodeString usCSVs = "3,4,5,6";

I need to store these values in std::vector < int>. What would be the best possible way of achieving the above functionali开发者_如何学Cty.

Regards, JS


You can use std::istream_iterator to parse the string. Before that you need to replace all delimiters to spaces.

 std::vector<int> myarr;
 std::string int_str = "3,4,5,6";
 std::replace( int_str.begin(), int_str.end(), ',', ' ' );
 std::stringstream in( int_str );
 std::copy( std::istream_iterator<int>(in), std::istream_iterator<int>(), std::back_inserter( myarr ) );

For UNICODE version it will look like:

 std::wstring int_str = L"3,4,5,6";
 std::replace( int_str.begin(), int_str.end(), L',', L' ' );
 std::wstringstream in( int_str );
 std::copy( std::istream_iterator<int, wchar_t>(in), std::istream_iterator<int, wchar_t>(), std::back_inserter( myarr ) );


Parse the string, first of all. You could iterate through it using std::string::find, that returns a position. You should find the delimiter - ','. Then, get the substring, closed between two commas and use std::stringstream. Done

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜