2012-01-02 61 views
0

我不能在網上找到,所以我最有可能在任何地方這是不是解決問題的正確方法,但也許:矢量 - 存儲值的返回部分?

我得到了一類具有值一個 ,我將這兩個存儲在一個集體向量中。有沒有辦法只能從矢量內訪問價值A?或者我需要爲這些值創建單獨的向量?

有人想看看我的代碼的一部分,所以在這裏:

class Read{ 
    friend ostream &operator<<(ostream &,const Read &); 
    public: 
     Read(char,float,float,float); 
     ~Read(); 
    private: 
     char objekt_; 
     float x_, y_, r_; 
}; 

int main(){ 
    vector<Read> v_read; 

    while(fin >> objekt >> x >> y >> r){ 
     v_read.push_back(Read(objekt, x, y, r)); 
    } 

    return 0; 
} 

出從向量我想訪問向量的每個部分我objekt_值。

+1

矢量的每個成員都是單個值。如果這個值是你的類,那麼你可以訪問它的內部。如果這個值是A或B--那麼它就是A或B.可能你可以在代碼片段中顯示你的意思? – littleadv 2012-01-02 04:21:51

回答

1

鑑於在我們可以做的事情,如結構兩件事struct個向量:

#include <vector> 
#include <algorithm> 
#include <boost/bind.hpp> 
#include <iterator> 
#include <iostream> 

struct test { 
    int a; 
    double b; 
}; 

int main() { 
    std::vector<test> vec = {{0, 0.1}, {1, 0.2}}; 

    // Copy the a's to another iterator 
    std::transform(vec.begin(), vec.end(), 
       std::ostream_iterator<int>(std::cout, "\n"), 
       boost::bind(&test::a,_1)); 

    // and the b's to another iterator 
    std::transform(vec.begin(), vec.end(), 
       std::ostream_iterator<double>(std::cout, "\n"), 
       boost::bind(&test::b,_1)); 

    // or just copy them into another vector 
    std::vector<int> veca; 
    veca.reserve(vec.size()); 
    std::transform(vec.begin(),vec.end(), 
       std::back_inserter(veca), 
       boost::bind(&test::a,_1)); 
} 

若要在給定std::vector所有條目的每個結構中的一部分工作。

1

如果A和B值存儲在向量的不同部分中,則可以使用一對迭代器來指示要處理的範圍。很像開始和結束給你的整個向量的範圍。