【问题标题】:parse string to vector of int将字符串解析为 int 的向量
【发布时间】:2014-01-06 16:27:24
【问题描述】:

我有一个字符串,其中包含一些用空格分隔的整数。例如

string myString = "10 15 20 23";

我想将其转换为整数向量。所以在例子中向量应该相等

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

我该怎么做?对不起,愚蠢的问题。

【问题讨论】:

  • 使用boost::split_regex
  • @juanchopanza 你能否解释一下拆分成 strings 与拆分成 vector of int 是一样的?
  • @jrok 仅仅拆分字符串和拆分字符串同时转换类型之间存在显着差异。
  • @Shafik_Yaghmour 我知道有很强的重叠 - 但那些肯定不是重复的。
  • @Christopher_Creutzig 没有一个关于所谓重复问题的答案会返回int向量

标签: c++ string vector


【解决方案1】:

您可以使用std::stringstream。除了其他包含之外,您还需要 #include &lt;sstream&gt;

#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 );

【讨论】:

  • 我认为添加包含语句会使这个答案更好。
  • 我的意思是所有 (+vector) - 以及编译所需的 using declarations。我会准备好我的 (+1) :)
  • ...顺便说一句:我喜欢这个 while (iss &gt;&gt; number) :-)
  • 太棒了! (+1d) 另一种选择是using std::vector; using std::stringstream; using std::string;
  • @mskoryk 那么你可能想accept this answer?
【解决方案2】:
std::string myString = "10 15 20 23";
std::istringstream is( myString );
std::vector<int> myNumbers( ( std::istream_iterator<int>( is ) ), ( std::istream_iterator<int>() ) );

如果向量已经定义,则代替最后一行

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

【讨论】:

  • 将最后一行写成 std​​::vector myNumbers( ( std::istream_iterator( is ) ), std::istream_iterator() 会更正确);也就是将第一个参数括在括号中。否则,它将是一个函数声明,而不是向量定义。:)
  • 或者您可以使用旨在解决该问题的初始化列表构造。 std::vector&lt;int&gt; myNumbers{ std::istream_iterator&lt;int&gt;( is ), std::istream_iterator&lt;int&gt;() };
【解决方案3】:

这几乎是另一个答案的重复。

#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, " "));
}

【讨论】:

  • 无需使用std::copy。因为std::vector 有一个构造函数,它接受两个迭代器(就像 std::copy 一样)。
  • 另外,用于输出的 good old for loop 最好不要包含在此处,因为它不容易
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
相关资源
最近更新 更多