msk*_*ryk 18 c++ string vector
我有一个字符串,其中包含一些用空格分隔的整数.例如
string myString = "10 15 20 23";
Run Code Online (Sandbox Code Playgroud)
我想将它转换为整数向量.所以在这个例子中,向量应该是相等的
vector<int> myNumbers = {10, 15, 20, 23};
Run Code Online (Sandbox Code Playgroud)
我该怎么做?抱歉愚蠢的问题.
Abh*_*sal 26
你可以用std::stringstream
.您需要#include <sstream>
与其他包含区分开来.
#include <sstream>
#include <vector>
#include <string>
std::string myString = "10 15 20 23";
std::stringstream iss( myString );
int number;
std::vector<int> myNumbers;
while ( iss >> number )
myNumbers.push_back( number );
Run Code Online (Sandbox Code Playgroud)
std::string myString = "10 15 20 23";
std::istringstream is( myString );
std::vector<int> myNumbers( std::istream_iterator<int>( is ), std::istream_iterator<int>() );
Run Code Online (Sandbox Code Playgroud)
如果已经定义了向量,则代替最后一行
myNumbers.assign( std::istream_iterator<int>( is ), std::istream_iterator<int>() );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14835 次 |
最近记录: |