2015-09-02 62 views
0

中的.cpp我最初的實現方法是這樣的:如何利用編寫向量的矢量通用打印C++

using namespace std; 
... 
template <typename T> 
void print2dvector(vector<vector<T> > v) { 
    for(int i = 0; i < v.size(); i++) { 
     for(int j = 0; j < v[i].size(); j++) { 
      cout << v[i][j] << " "; 
     } 
     cout << endl; 
    } 
} 

在.h文件中聲明如下

template <typename T> void print2dvector(std::vector<std::vector<T> > v); 

這裏是我如何使用它,

print2dvector<int>(vec_of_vec); 

編譯階段通過,但在連接階段失敗。錯誤如下:

Undefined symbols for architecture x86_64: 
    "void print2dvector<int>(std::__1::vector<std::__1::vector<int, std::__1::allocator<int> >, std::__1::allocator<std::__1::vector<int, std::__1::allocator<int> > > >)", referenced from: 
    spiral_matrix_ii_Challenge::Execute() in spiral_matrix_ii.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

請讓我知道,如果我錯過任何概念在實現這一點。

+5

是在頭文件或實現文件中的函數? –

+0

[OT]:您可以將向量作爲常量引用傳遞以避免複製。 – Jarod42

+0

@Piotr該函數在cpp文件中實現並在頭文件中定義。 – lordofire

回答

3

鏈接錯誤意味着您的模板沒有實例化,鏈接器也無法鏈接這些符號。正如@Piotr Skonticki所說,解決這個問題的最佳選擇是在使用的地方或頭文件中實現它。有關更多信息,請參閱this

關於代碼 - 我會寫這樣的:

#include <vector> 
#include <iterator> 
#include <algorithm> 
#include <iostream> 

template<typename T> 
void printVector(const T& t) { 
    std::copy(t.cbegin(), t.cend(), std::ostream_iterator<typename T::value_type>(std::cout, ", ")); 
} 

template<typename T> 
void printVectorInVector(const T& t) { 
    std::for_each(t.cbegin(), t.cend(), printVector<typename T::value_type>); 
} 

int main() { 
    std::vector<int> a = {1, 3, 5, 7, 9}; 
    std::vector<std::vector<int>> b; 
    b.push_back(a); 
    b.push_back(a); 
    printVectorInVector(b); 
    return 0; 
} 

我覺得這是比你更好的解決方案,因爲:

  1. 它不依賴於一個迭代集合類型(它可以是向量,列表或任何具有迭代器和類似於迭代器接口的類)。
  2. 它不依賴於值類型 - 它始終從可迭代集合(T::value_type)獲取適當的值類型。
  3. 它也避免了對象複製,因爲它通過const引用獲取它。
+0

完美地解決了我的問題,thanx :) – lordofire