【问题标题】:vector of integers整数向量
【发布时间】:2011-12-03 20:39:06
【问题描述】:

我想将向量转换为整数。我可以使用

输出向量
vector <int> iV;

iV.push_back(3);
iV.push_back(8);
iV.push_back(6);

copy(iV.begin(),iV.end(),ostream_iterator<int>(cout,""))

但是我怎样才能把它变成一个 int 呢?

编辑:使用 stringstream 对我正在做的事情很好。 我确实想通过 cout 看看它到底是什么样子。 我不想要精确的 int by int 我的意思是一个单一的 int 所以在我的例子中它将是一个等于 386 的 int。 感谢大家的帮助,非常感谢。

【问题讨论】:

  • 您希望int 在这种情况下包含什么?
  • @IgnacioVazquez-Abrams 和他通过 cout 看到的一样吗?
  • @Acebond:你的意思是你想通过 int 提取值 int ?是吗?

标签: c++ vector int


【解决方案1】:

把它写到 stringstream 然后像这样读取它:

std::stringstream strStream;
copy(iV.begin(),iV.end(),ostream_iterator<int>(strStream,""));
int myInt;
strStream >> myInt;

【讨论】:

  • 非常感谢。精美的作品和史诗般的响应时间。
  • 这不是很有效。为什么要通过字符串?
  • @Hasan Khan:常识表明,当高效地做某事同样容易(或更容易)时,你应该这样做。至少有一个警告会很好。
  • @Hasan Khan:当我评论你的代码效率低下时,我并不是要冒犯你。在可读性和可维护性的主题上,涉及迭代、乘以 10 和加法的任何一天都胜过 ostringstreams。
【解决方案2】:

我不确定这是否是您的意思,但您可以这样做:

int * ip = &iv[0];

然后访问ip[0]ip[1]

【讨论】:

    【解决方案3】:
    int x;
    for(vector<int>::const_iterator i = iV.begin(); i != iV.end(); i++)
        x = *i;
    

    【讨论】:

      【解决方案4】:

      试试这样的:

      int total = 0;
      for(vector<int>::const_iterator i = iV.begin(); i != iV.end(); ++i)
          total = total*10 + *i;
      

      【讨论】:

      • 当然,这可能只适用于单位数整数。
      • @Peter:是的。我不自觉地假设向量包含数字。
      • 你需要乘以的东西可能会用类似的东西来计算:n &gt; 0 ? std::pow(10, int(std::log10(n) + 1)) : 10 (ideone.com/9efpn)
      • 谢谢史蒂夫,这似乎更有效率。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多