2017-06-14 13 views
1

私は、以下の機能を持っている:ベクトル<double>の機能にNULLを返すことはできますか?

/* Calculate if there is an intersection with given intial position and 
    direction */ 
vector<double> intersection(vector<double> startPos, vector<double> direction) 
{ 
    if(there is intersection) 
     return (intersection coordinates); 
    else { 
     return NULL; 
    } 
} 

は、私がこれを行うと、交差点が存在するかどうNULLに対してチェックすることができ:

vector<double> v = intersection(pos, dir); 
if(v == NULL) 
    /* Do something */ 
else 
    /* Do something else */ 

これが/悪いコーディングの練習を許可されていない場合は、別の方法で私は何でありますこれについて行くかもしれない?

+10

ベクトルはNULLにすることはできませんが、空にすることはできます()。 –

+0

この質問が表示される場合があります。https://stackoverflow.com/q/29460651/10077 –

+1

通常、NULLはポインタとともに使用されます。しかし、空のベクトルを返し、それが空であれば反対側を検証することができます。 – Rosme

答えて

3

NULLは実際にはポインタの概念です。私たちはコンテナを持っているので、コンテナがemptyかどうかをチェックすることができます。そうであれば、要素がないことがわかります。要素がなければ、処理する要素があることがわかります。それはあなたが

vector<double> intersection(vector<double> startPos, vector<double> direction) 
{ 
    if(there is intersection) 
     return (intersection coordinates); 
    else { 
     return {}; // this means return a default constructed instance 
    } 
} 

のようなコードを記述して、あなたが

vector<double> v = intersection(pos, dir); 
if(v.empty()) 
    /* Do something */ 
else 
    /* Do something else */ 

のようにそれを使用することができますまた、あなたが設定された交差点を取得したい場合は、std::set_intersectionを使用して

のようにそれを使用できることに注意することができます
#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <iterator> 
int main() 
{ 
    std::vector<int> v1{1,2,3,4,5,6,7,8}; 
    std::vector<int> v2{  5, 7, 9,10}; 
    std::sort(v1.begin(), v1.end()); 
    std::sort(v2.begin(), v2.end());  
    std::vector<int> v_intersection;  
    std::set_intersection(v1.begin(), v1.end(), 
          v2.begin(), v2.end(), 
          std::back_inserter(v_intersection)); 
    for(int n : v_intersection) 
     std::cout << n << ' '; 
} 

出力:

5 7 
関連する問題