简体   繁体   English

将字符串解析为 int 向量

[英]parse string to vector of int

I have a string which contains some number of integers which are delimited with spaces.我有一个字符串,其中包含一些用空格分隔的整数。 For example例如

string myString = "10 15 20 23";

I want to convert it to a vector of integers.我想将其转换为整数向量。 So in the example the vector should be equal所以在这个例子中,向量应该相等

vector<int> myNumbers = {10, 15, 20, 23};

How can I do it?我该怎么做? Sorry for stupid question.对不起,愚蠢的问题。

You can use std::stringstream .您可以使用std::stringstream You will need to #include <sstream> apart from other includes.除了其他包含之外,您还需要#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 );
std::string myString = "10 15 20 23";
std::istringstream is( myString );
std::vector<int> myNumbers( ( std::istream_iterator<int>( is ) ), ( std::istream_iterator<int>() ) );

Or instead of the last line if the vector was already defined then或者如果向量已经定义,则代替最后一行

myNumbers.assign( std::istream_iterator<int>( is ), std::istream_iterator<int>() );

This is pretty much a duplicate of the other answer now.这现在几乎是另一个答案的重复。

#include <iostream>
#include <vector>
#include <iterator>
#include <sstream>

int main(int argc, char* argv[]) {
    std::string s = "1 2 3 4 5";
    std::istringstream iss(s);
    std::vector<int> v{std::istream_iterator<int>(iss),
                       std::istream_iterator<int>()};
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM