Thinking in C++

My C++ code snips.

Posts Tagged ‘convert vector to map’

Vector to map C++

Posted by Abhi on April 16, 2012

Here is a code snippet to insert a vector into a map. The function takes a vector and a map<string, vector > as argument. The first element of the vector is treated as the key, and the rest is the value. This should be useful when retrieving unknown number of values from a file [settings for example].

  • Read the file, one line at a time.
  • ┬áSplit the line based on whatever divider you choose and store it in a vector of string.
  • ┬áThen use this function to insert the vector into a map.

Header:

#ifndef vectorMap_H
#define vectorMap_H

#include <string>
#include <map>
#include <vector>

void vectorMap(const std::vector<std::string> &, std::map<std::string,std::vector<std::string> > &);

#endif

Implementation:

#include "vectorMap.h"

using std::map;
using std::string;
using std::vector;

typedef vector<string> vec_str;
typedef map<string, vector<string> > map_str;

void vectorMap(const std::vector<std::string> &v_str, std::map<std::string,std::vector<std::string> > &m_str)
{
 string key;
 for(vec_str::const_iterator iter= v_str.begin(); iter != v_str.end(); ++iter )
 {
 if(iter == v_str.begin())
 {
 key = *iter;
 continue;
 }
 m_str[key].push_back(*iter);
 }
}
Advertisements

Posted in C++ | Tagged: , | Leave a Comment »