2014-06-21 9 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; 
} 

편집 :

내가 거기 채우기 기능 내부 표준에 의해 그것을 할 방법 :: is_same을 below.Is을 같이 코드를 수정 한?

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::generate 또는 std::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; 
}