【问题标题】:How to cout a vector of strings?如何计算字符串向量?
【发布时间】:2015-05-07 17:02:04
【问题描述】:

在控制台上打印出字符串向量的最简单方法是什么?

我得到了这样的东西

map < int, vector<string>>

我想将值打印到用户给定的键。

typemap::iterator p1;

cin >> i
for (pointer = map.begin(); pointer != map.end(); ++pointer)
{
if ((pointer->first) == i)
{
//The program should print the values right here.
}
}

【问题讨论】:

标签: c++ string vector output cout


【解决方案1】:

带有循环。并且不要遍历地图来查找密钥。

auto found = map.find(i);
if (found != map.end()) {
    for (string const & s : found->second) {
        cout << s << ' ';
    }
}

【讨论】:

  • 天哪,流输出迭代器的时代已经过去了。 :) 使用基于范围的循环更短、更简单、更清晰。
  • 谢谢,这对我来说是一种新方法。所以我必须玩一点。
【解决方案2】:

你可以使用 std::ostream_iterator

#include <algorithm>
#include <iterator>
/* .... */
auto found = map.find(i);
if (found != map.end()) {
    std::copy(found->second.begin(), 
              found->second.end(),
              std::ostream_iterator<std::string>(std::cout," "));
}

更多信息在这里: http://www.cplusplus.com/reference/iterator/ostream_iterator/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多