开发者

How to loop through a map and assign the value to an array in C++?

I have a map<id,age>,; how to get the age of each <id,age> pair, and assign the age to a C-style array in C++?

what is the efficient way to do it? I mean how to fill the C-style array in the same order as map?开发者_如何转开发


If you decide to stick with the fixed array approach

//Assuming both id and age are integers
map<int,int> myMap; // Your id and age map
map<int,int>::iterator it;
int myList[100];
int i = 0;
for(it = myMap.begin(); (i < 100 && it != myMap.end()); it++)
{
  myList[i++] = (*it).second;
}

A MUCH better approach is to use a vector instead of an array

//Assuming both id and age are integers
map<int,int> myMap; // Your id and age map
map<int,int>::iterator it;
vector<int> myList;
for(it = myMap.begin(); it != myMap.end(); it++)
{
  myList.push_back((*it).second);
}


If you can use c++11 you can use a lambda expression.

map<id,age> m;
std::list<age> l;
std::for_each(m.begin(), m.end(), [&l](std::pair<id,age> p){
    l.push_back(p.second);
});


I don't think what you're asking makes a lot of sense, but in the interest of just fiddling with C++ containers

(Note:: not using any C++0x features) http://ideone.com/Kf2du

Edit In response to the excellent comments by David Rodríguez, I have edited the code to avoid copying (see also https://ideone.com/7Oa5n):

#include <map>
#include <list>
#include <algorithm>
#include <iterator>
#include <vector>

typedef std::map<std::string, int> map_t;

int getage(const map_t::value_type& pair)
{ 
    return pair.second; 
}

int main()
{
     map_t agemap;
     agemap["jill"] = 13;
     agemap["jack"] = 31;

     std::list<int> agelist(agemap.size());
     std::transform(agemap.begin(), agemap.end(), agelist.begin(), getage);

     // or:
     std::vector<int> v;
     std::transform(agemap.begin(), agemap.end(), std::back_inserter(v), getage);

}

By popular demand, and just to spell it out:

int age_array[10];
std::transform(agemap.begin(), agemap.end(), age_array, getage);

or even

int *dyn_array = new int[agemap.size()];
std::transform(agemap.begin(), agemap.end(), dyn_array, getage);

// ...
delete[] dyn_array;


You've stated you want a C array and I'll answer particularly your request.

  std::map<int,int> some_map;

  int * c_array=new int[some_map.size()];
  size_t k=0;
  for (std::map<int,int>::iterator i=some_map.begin();
       i != some_map.end(); ++i)
    {
      c_array[k++]=(*i).second;
    }
  delete[] c_array;

As others have stated, the standard for C++ would be the vector. I would add, you would want to reserve the proper space before-hand since you already know it. It can be reserved via the c-tor for a vector.

  std::map<int,int> some_map;
  std::vector<int>  some_vector(some_map.size());
  for (std::map<int,int>::iterator i=some_map.begin();
       i != some_map.end(); ++i)
    {
      some_vector.push_back((*i).second);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜