Thinking in C++

My C++ code snips.

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.


#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> > &);



#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;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: