std :: map에서 모든 키 (또는 값)를 검색하여 벡터에 넣는 방법은 무엇입니까? keyValuePair) const {

이것은 내가 나오는 가능한 방법 중 하나입니다.

struct RetrieveKey
{
    template <typename T>
    typename T::first_type operator()(T keyValuePair) const
    {
        return keyValuePair.first;
    }
};

map<int, int> m;
vector<int> keys;

// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());

// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n"));

물론 다른 functor RetrieveValues 를 정의하여 맵에서 모든 값을 검색 할 수도 있습니다 .

이것을 쉽게 달성 할 수있는 다른 방법이 있습니까? (왜 std :: map에 멤버 함수가 포함되어 있지 않은지 항상 궁금합니다.)



답변

솔루션이 작동해야하지만 동료 프로그래머의 기술 수준에 따라 읽기 어려울 수 있습니다. 또한 기능을 호출 사이트에서 멀리 이동시킵니다. 유지 관리를 좀 더 어렵게 만들 수 있습니다.

당신의 목표가 키를 벡터로 가져 오거나 cout으로 인쇄하여 두 가지를 모두 수행하는 것이 확실하지 않습니다. 다음과 같이 시도해보십시오.

map<int, int> m;
vector<int> v;
for(map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {
  v.push_back(it->first);
  cout << it->first << "\n";
}

또는 Boost를 사용하는 경우 더 간단합니다.

map<int,int> m;
pair<int,int> me; // what a map<int, int> is made of
vector<int> v;
BOOST_FOREACH(me, m) {
  v.push_back(me.first);
  cout << me.first << "\n";
}

개인적으로 BOOST_FOREACH 버전은 타이핑이 적고 수행중인 작업에 대해 매우 명확하기 때문에 좋아합니다.


답변

//c++0x too
std::map<int,int> mapints;
std::vector<int> vints;
vints.reserve(mapints.size());
for(auto const& imap: mapints)
    vints.push_back(imap.first);


답변

부스트 범위 어댑터 이 목적은 :

vector<int> keys;
// Retrieve all keys
boost::copy(m | boost::adaptors::map_keys, std::back_inserter(keys));

값을 추출하기위한 비슷한 map_values ​​범위 어댑터가 있습니다.


답변

C ++ 0x는 우리에게 더욱 훌륭한 솔루션을 제공했습니다.

std::vector<int> keys;

std::transform(
    m_Inputs.begin(),
    m_Inputs.end(),
    std::back_inserter(keys),
    [](const std::map<int,int>::value_type &pair){return pair.first;});


답변

C ++ 11을 사용하는 @ DanDan의 대답은 다음과 같습니다.

using namespace std;
vector<int> keys;

transform(begin(map_in), end(map_in), back_inserter(keys),
            [](decltype(map_in)::value_type const& pair) {
    return pair.first;
}); 

사용 및 C (@ ivan.ukr으로 명시된) 14 ++ 우리는 바꿀 수 decltype(map_in)::value_typeauto.


답변

SGI STL에는이라는 확장자가 select1st있습니다. 표준 STL에없는 것은 너무 나쁘다!


답변

귀하의 솔루션은 훌륭하지만 반복기를 사용하여 수행 할 수 있습니다.

std::map<int, int> m;
m.insert(std::pair<int, int>(3, 4));
m.insert(std::pair<int, int>(5, 6));
for(std::map<int, int>::const_iterator it = m.begin(); it != m.end(); it++)
{
    int key = it->first;
    int value = it->second;
    //Do something
}