gpt4 book ai didi

c++ - 打印 vector 到矩阵

转载 作者:行者123 更新时间:2023-11-30 05:30:18 32 4
gpt4 key购买 nike

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

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';
}

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

最佳答案

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

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

关于c++ - 打印 vector <string> 到矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36009949/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com