2016-03-15 71 views
1

我是新的C++。我試圖實現一個方法,它必須將一個向量打印到一個矩陣中,但是我的實現非常愚蠢。 下面是一個exampe應該如何工作:它具有4個字符串打印矢量<string>矩陣

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

我真的不明白是什麼我做錯了。

+2

你看了,你使用的事情應該如何工作的?看起來你根本不明白你在做什麼。否則...你不明白什麼?發生什麼事?目前你說「這是任務,我的代碼不起作用」。 – luk32

+0

@ luk32是的,我真的不明白我在做什麼。 – Lemmy

+0

如果在打印任何內容之前知道最長字符串的長度,這應該相當簡單。 – Logicrat

回答

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| 
------------- 
+0

謝謝!這一個幫助。 – Lemmy