Search code examples
c++c++11stlstdvectorstdset

STL way of creating/filling std::set from std::vector


I want to create and fill a set from the contents of a member variable of each entry of a vector. This is what I am doing:

struct S { int i; };

int main()
{
    std::vector<S*> structPtrs;

    // code to fill the above vector

    // create set from the above vector
    std::set<int> setInts;
    for (auto it = structPtrs.begin(); it != structPtrs.end(); ++it)
    {
        setInts.insert((*it)->i);
    }
}

Is there an STL way to do it? Or via any available method(s) in <algorithm>?


Solution

  • There is one other way you can do this. If you add conversion operator to int to your struct you can just use range constructor directly

    #include <iostream>
    #include <set>
    #include <vector>
    using namespace std;
    
    struct test {int i; operator int() {return i;}};
    
    int main() {
        vector<test> v;
            v.push_back(test{433});
            v.push_back(test{533});
            set<int> s(v.begin(), v.end());
            cout << *(++s.begin());
        return 0;
    }
    

    https://www.ideone.com/qJwtwc