【问题标题】:How to convert a vector<int> to string in C++ [closed]如何在 C++ 中将 vector<int> 转换为字符串 [关闭]
【发布时间】:2015-08-02 00:48:34
【问题描述】:

假设我有一个vector&lt;int&gt;,我想把它转换成字符串,我该怎么办? 我在网上搜索得到的是

std::ostringstream oss;

if (!vec.empty())
{
  // Convert all but the last element to avoid a trailing ","
 std::copy(vec.begin(), vec.end()-1,
    std::ostream_iterator<int>(oss, ","));

// Now add the last element with no delimiter
oss << vec.back();
}

但我无法理解它的含义或它是如何工作的。还有其他简单易懂的方法吗?

【问题讨论】:

  • 您对它的工作原理具体有什么不明白的地方?
  • 我不明白这句话的作用std::copy(vec.begin(), vec.end()-1, std::ostream_iterator&lt;int&gt;(oss, ","));
  • 有人可以建议任何其他方法吗?
  • @ronilp 不需要另一种方式,这个方式很好,std::copy 是最易读和最惯用的复制方式。 “我不明白”不是切换实现的理由。您需要阅读文档。
  • 0x499602D2 建议的方式更容易理解。我一直在寻找这样的方式。

标签: c++ string vector iterator ostream


【解决方案1】:

仅当您想在每个插入的整数后添加分隔符时才需要该代码,但即使那样它也不必那么复杂。一个简单的循环和to_string 的使用更具可读性:

std::string str;

for (int i = 0; i < vec.size(); ++i) {
    str += std::to_string(vec[i]);
    if (i+1 != vec.size()) { // if the next iteration isn't the last
        str += ", "; // add a comma (optional)
    }
}

【讨论】:

  • 假设此时不需要逗号,str += "" 将是变化,对吧?
  • @ronilp 那么你根本不需要if 语句,只需要str += to_string(vec[i]) 部分。
【解决方案2】:

以数字为界,

std::vector<int> v {0, 1, 2, 3, 4};
std::string s("");
for(auto i : v)
    s += std::to_string(i);

使用逗号分隔符

std::vector<int> v {0, 1, 2, 3, 4};
std::string s("");
for(auto i : v)
    s += std::to_string(i) + ",";
s.pop_back();

【讨论】:

    猜你喜欢
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    相关资源
    最近更新 更多