将矢量<string>打印到矩阵

时间:2016-03-15 11:25:39

标签: c++

我是c ++的新手。我正在尝试实现一个必须将向量打印到矩阵的方法,但我的实现工作非常愚蠢。 这是一个例子,它应该如何工作:我有一个有4个字符串的向量

std::vector<std::string> vec = {"abcd", "def", "ghi", "jkld"};

并且输出应该是一个矩阵,其中元素是右对齐的并且只有2列。列shold具有相等的宽度,宽度等于最长的字符串+ 1.像这样:

-------------
| abcd|  def|
|  ghi| jkld|
-------------

这就是我所拥有的:

void print_table(std::ostream& out, const std::vector<std::string>& vec){
        for (const auto& array : vec)
            out.width(); out << "-" << std::endl;

        for (auto x : vec) {
               out.width(); out<<"|" << std::right  << x<< " |";
               out.width(); out <<"|" << std::right  << x<< " | ";
        }
        out.width(); out << "-" << '\n';
}

我真的不明白我做错了什么。

1 个答案:

答案 0 :(得分:1)

根据要求。也适用于任何长度的矢量,包括奇数长度。

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>

std::ostream& print_tab(std::ostream& os, const std::vector<std::string>& vs)
{
    auto colwidth = std::max_element(std::begin(vs),
                                     std::end(vs),
                                     [](const auto& s1, const auto&s2)
                                     {return s1.length() < s2.length(); })->length();

    auto table_width = (colwidth + 1) * 2 + 3;

    os << std::string(table_width, '-');
    auto i = std::begin(vs);
    while (i != std::end(vs) )
    {
        os << std::endl << "|" << std::setfill(' ') << std::setw(colwidth + 1) << std::right << *i++;
        os << "|";
        if (i != std::end(vs)) {
            os << std::setfill(' ') << std::setw(colwidth + 1) << std::right << *i++;
        }
        else {
            os << std::string(colwidth + 1, ' ');
        }
        os << '|';
    }
    os << std::endl << std::string(table_width, '-');


    return os;
}

int main()
{
    using namespace std;

    auto tab = vector<string> { "abcd", "def", "ghi", "jkld" };
    print_tab(cout, tab) << std::endl;

    return 0;
}

预期产出:

-------------
| abcd|  def|
|  ghi| jkld|
-------------
相关问题