2014-06-21 62 views
0

我想編寫一個函數,用隨機值填充向量。用隨機值填充通用向量

T =數字和Pnt結構。

我的問題:如何用隨機值填充模板向量?

#include <vector> 
using namespace std; 

class Pnt{ 
public: 
    int x, y; 
    Pnt(int _x, int _y) :x(_x), y(_y){} 
}; 
template <typename T> 
void fill(vector<T>& vec){ 
    for (auto& value : vec) 
    // how to fill with random values 

} 
int main() { 
    vector<Pnt> arr_pnt(10); 
    fill(arr_pnt); 

    vector<int> arr_int(10); 
    fill(arr_int); 

    return 0; 
} 

編輯:

我已經修改,如圖below.Is有沒有辦法通過STD做:: is_same fill函數裏面的代碼?

class Pnt{ 
public: 
    int x, y; 
    Pnt(int _x, int _y) :x(_x), y(_y){} 
}; 
void getRnd(Pnt& p){ 
    p.x = rand(); 
    p.y = rand(); 
} 
void getRand(int& value){ 
    value = rand(); 
} 
template <typename T> 
void fill(vector<T>& vec){ 
    for (auto& value : vec) 
    getRand(value); 


} 
int main() { 
    vector<Pnt> arr_pnt(10); 
    fill(arr_pnt); 

    vector<int> arr_int(10); 
    fill(arr_int); 

    return 0; 
} 
+0

似乎缺失的一個組件是隨機數發生器。你有什麼嘗試? – Potatoswatter

+0

編寫一個隨機生成一個值的函數,然後使用'std :: generate'。 –

+1

在這種情況下,我可能會使用'std :: generate_n'來代替。 –

回答

3

無需編寫自己的補法,使用std::generatestd::generate_n

// use of std::rand() for illustration purposes only 
// use a <random> engine and distribution in real code 
int main() { 
    vector<Pnt> arr_pnt(10); 
    std::generate(arr_pnt.begin(), arr_pnt.end(), [](){ return Pnt{std::rand(), std::rand()};}); 

    vector<int> arr_int; 
    std::generate_n(std::back_inserter(arr_int), 10, std::rand); 

    return 0; 
}