Карта копии оценивает вектору в STL

Попробуйте это:

select distinct A from [dbo].[table] where A not in ( select A from [dbo].[table] where C <> 0)

72
задан Gilad Naor 21 April 2009 в 07:30
поделиться

7 ответов

Вы не можете легко использовать диапазон здесь, потому что итератор, который вы получаете от карты, ссылается на std :: pair где итераторы, которые вы использовали бы для вставки в вектор, ссылаются на объект типа, хранящегося в векторе, который является (если вы отбрасываете ключ) не парой.

Я действительно не думаю, что он получает много чище, чем очевидное:

#include <map>
#include <vector>
#include <string>
using namespace std;

int main() {
    typedef map <string, int> MapType;
    MapType m;  
    vector <int> v;

    // populate map somehow

    for( MapType::iterator it = m.begin(); it != m.end(); ++it ) {
        v.push_back( it->second );
    }
}

, который я, вероятно, переписал бы как шаблонную функцию, если бы собирался использовать его более одного раза. Примерно так:

template <typename M, typename V> 
void MapToVec( const  M & m, V & v ) {
    for( typename M::const_iterator it = m.begin(); it != m.end(); ++it ) {
        v.push_back( it->second );
    }
}
55
ответ дан 24 November 2019 в 12:30
поделиться

Возможно, вы могли бы использовать std :: transform для этой цели. Возможно, я бы предпочел версию Neils, в зависимости от того, что является более читабельным.


Пример xtofl (см. Комментарии):

#include <map>
#include <vector>
#include <algorithm>
#include <iostream>

template< typename tPair >
struct second_t {
    typename tPair::second_type operator()( const tPair& p ) const { return p.second; }
};

template< typename tMap > 
second_t< typename tMap::value_type > second( const tMap& m ) { return second_t< typename tMap::value_type >(); }


int main() {
    std::map<int,bool> m;
    m[0]=true;
    m[1]=false;
    //...
    std::vector<bool> v;
    std::transform( m.begin(), m.end(), std::back_inserter( v ), second(m) );
    std::transform( m.begin(), m.end(), std::ostream_iterator<bool>( std::cout, ";" ), second(m) );
}

Очень общий, не забывайте отдавать ему должное, если вы находите это полезным.

53
ответ дан 24 November 2019 в 12:30
поделиться

Одним из способов является использование функтора:

 template <class T1, class T2>
    class CopyMapToVec
    {
    public: 
        CopyMapToVec(std::vector<T2>& aVec): mVec(aVec){}

        bool operator () (const std::pair<T1,T2>& mapVal) const
        {
            mVec.push_back(mapVal.second);
            return true;
        }
    private:
        std::vector<T2>& mVec;
    };


int main()
{
    std::map<std::string, int> myMap;
    myMap["test1"] = 1;
    myMap["test2"] = 2;

    std::vector<int>  myVector;

    //reserve the memory for vector
    myVector.reserve(myMap.size());
    //create the functor
    CopyMapToVec<std::string, int> aConverter(myVector);

    //call the functor
    std::for_each(myMap.begin(), myMap.end(), aConverter);
}
1
ответ дан 24 November 2019 в 12:30
поделиться

Используя лямбды, можно выполнить следующее:

{
   std::map<std::string,int> m;
   std::vector<int> v;
   v.reserve(m.size());
   std::for_each(m.begin(),m.end(),
                 [&v](const std::map<std::string,int>::value_type& p) 
                 { v.push_back(p.second); });
}
18
ответ дан 24 November 2019 в 12:30
поделиться

Вот что я бы сделал.
Также я бы использовал функцию шаблона, чтобы упростить конструирование select2nd.

#include <map>
#include <vector>
#include <algorithm>
#include <memory>
#include <string>

/*
 * A class to extract the second part of a pair
 */   
template<typename T>
struct select2nd
{
    typename T::second_type operator()(T const& value) const
    {return value.second;}
};

/*
 * A utility template function to make the use of select2nd easy.
 * Pass a map and it automatically creates a select2nd that utilizes the
 * value type. This works nicely as the template functions can deduce the
 * template parameters based on the function parameters. 
 */
template<typename T>
select2nd<typename T::value_type> make_select2nd(T const& m)
{
    return select2nd<typename T::value_type>();
}

int main()
{
    std::map<int,std::string>   m;
    std::vector<std::string>    v;

    /*
     * Please note: You must use std::back_inserter()
     *              As transform assumes the second range is as large as the first.
     *              Alternatively you could pre-populate the vector.
     *
     * Use make_select2nd() to make the function look nice.
     * Alternatively you could use:
     *    select2nd<std::map<int,std::string>::value_type>()
     */   
    std::transform(m.begin(),m.end(),
                   std::back_inserter(v),
                   make_select2nd(m)
                  );
}
8
ответ дан 24 November 2019 в 12:30
поделиться

Если вы используете библиотеки boost , вы можете использовать boost :: bind для доступа ко второму значению пары следующим образом:

#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>

int main()
{
   typedef std::map<std::string, int> MapT;
   typedef std::vector<int> VecT;
   MapT map;
   VecT vec;

   map["one"] = 1;
   map["two"] = 2;
   map["three"] = 3;
   map["four"] = 4;
   map["five"] = 5;

   std::transform( map.begin(), map.end(),
                   std::back_inserter(vec),
                   boost::bind(&MapT::value_type::second,_1) );
}

Это решение основано на сообщении Майкла Гольдштейна в списке рассылки boost .

23
ответ дан 24 November 2019 в 12:30
поделиться

Я думал, что это должно быть

std::transform( map.begin(), map.end(), 
                   std::back_inserter(vec), 
                   boost::bind(&MapT::value_type::first,_1) ); 
2
ответ дан 24 November 2019 в 12:30
поделиться
Другие вопросы по тегам:

Похожие вопросы: