所以我需要创建一个方法来获取我创建的两张 ASCII 图片并并排打印它们,因此方法调用:
concatHz(Picture l, Picture r);
其中 Picture 是一个对象,它将 ASCII 图片作为字符串存储在字段 l.result 和 r.result 中。
如果 r 是
+------+
|This |
|is the|
|String|
+------+
我是:
This
is the
String
那么结果就是:
This +------+
is the|This |
String|is the|
|String|
+------+
我想过这样做的方法,但它们似乎太复杂,可能有更简单的方法。我正在考虑使用 for 循环遍历每个字符串行并打印第一个然后是第二个,但随后遇到了与上面的示例一样的索引错误问题。有没有一种我没有想到的简单方法可以做到这一点?
下面是创建底层ASCII图片的方法:
Picture Picture::create(std::vector<std::string> v){
Picture c; //default constructor called without parenthesis
c.picList=v;
c.result="";
int max1=0;
for(int i=0;i<v.size();i++){
if(v.at(i).length()>max1){
max1=v.at(i).length();
}
c.rows++;
c.result+=v.at(i)+"\n";
}
c.maxLen=max1;
return c;
}
最佳答案
不要将完整的图片生成为单个 std::string
,您需要访问构成每个 的各个
。这样,您可以运行一个循环,其中每次迭代输出填充到 std::string
值std::vector l.maxLen
个字符的下一个 l
字符串,然后输出下一个 r
字符串,然后输出一个换行符。当两张图片都用完时结束循环。
例如:
#include <string>
#include <vector>
class Picture
{
private:
std::vector<std::string> picList;
std::size_t maxLen;
public:
Picture();
Picture(const std::vector<std::string> &v);
static Picture create(const std::vector<std::string> &v);
std::size_t getMaxRowLen() const;
std::size_t getRows() const;
std::string getRow(std::size_t index) const;
// just in case you really need it
std::string getResult() const;
};
#include <iostream>
#include <sstream>
#include <iomanip>
Picture Picture::create(const std::vector<std::string> &v)
{
return Picture(v);
}
Picture::Picture()
: maxLen(0)
{
}
Picture::Picture(const std::vector<std::string> &v)
: picList(v), maxLen(0)
{
for(std::vector<std::string>::const_iterator iter = picList.begin(); iter != picList.end(); ++iter) {
if (iter->length() > maxLen) {
maxLen = iter->length();
}
}
}
std::size_t Picture::getMaxRowLen() const
{
return maxLen;
}
std::size_t Picture::getRows() const
{
return picList.size();
}
std::string Picture::getRow(std::size_t index) const
{
std::string row;
if (index < picList.size()) {
row = picList[index];
}
std::ostringstream oss;
oss << std::setw(maxLen) << std::left << std::setfill(' ') << row;
return oss.str();
}
std::string Picture::getResult() const
{
std::ostringstream oss;
for(std::vector<std::string>::const_iterator iter = picList.begin(); iter != picList.end(); ++iter) {
oss << std::setw(maxLen) << std::left << std::setfill(' ') << *iter << "\n";
}
return oss.str();
}
void concatHz(const Picture &l, const Picture &r)
{
std::size_t rows = std::max(l.getRows(), r.getRows());
for (std::size_t i = 0; i < rows; ++i) {
std::cout << l.getRow(i) << r.getRow(i) << "\n";
}
}
关于C++:如何并排打印两张ASCII图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40032368/