Reputation: 1
I have 2 char arrays like "const char *arr1[ArrSize] = {"Blah1", "Wibble1", "Shrug1"};". For putting them into a vector I found a nice quick solution:
void fillVecTest()
{
const int ArrSize = 3;
const char *arr1[ArrSize] = {"Blah1", "Wibble1", "Shrug1"};
const char *arr2[ArrSize] = {"Blah2", "Wibble2", "Shrug2"};
std::vector<std::string> vec1(arr1, arr1+ArrSize);
std::vector<std::string> vec2(arr2, arr2+ArrSize);
std::vector<std::string>::iterator l_It1Vec1;
std::vector<std::string>::iterator l_It = vec1.end();
l_It = find(vec1.begin(), vec1.end(), std::string("Blah1"));
if(l_It != vec1.end())
{
size_t l_pos = l_It - vec1.begin();
printf("found %s, pos=%u val: %s\n", l_It->c_str(),l_pos, vec2[l_pos].c_str());
}
}
Now I thought it should be also possible to put both directly into a map as arr1 is the key and arr2 is the value. I tried some ways but I didn't succeed.
void fillMapTest()
{
const int ArrSize = 3;
const char *arr1[ArrSize] = {"Blah1", "Wibble1", "Shrug1"};
const char *arr2[ArrSize] = {"Blah2", "Wibble2", "Shrug2"};
std::map<std::string,std::string> map1;//(pair(arr1,arr1), pair(arr1+ArrSize,arr2+ArrSize));
std::map<std::string,std::string>::iterator l_It1Map1;
//l_It1Map1 = find(map1.begin(), map1.end(), std::string("Blah1"));
if(l_It1Map1 != map1.end())
{
printf("found key: %s, val: %s\n",l_It1Map1->first.c_str(), l_It1Map1->second.c_str());
}
}
int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
fillVecTest();
fillMapTest();
return 0;
}
I think that just the commented lines in function "fillMapTest" would need to be solved. Constuctor and find don't work like I want.
Please has any STL expert an idea?
Upvotes: 0
Views: 1230
Reputation: 7249
std::map<std::string, std::string> m;
for(int i = 0; i < ArrSize; i++) {
std::pair<std::string, std::string> p =
std::make_pair(std::string(arr1[i]), std::string(arr2[i]));
m.insert(p);
}
If you really want to use the map constructor you need an iterator of pairs and the only way(i know) is to use a std::vector<std::pair<std::string, std::string> >::iterator
but this seems to be an unneeded extra step to get the same result.
#include <vector>
#include <map>
#include <string>
std::vector<std::pair<std::string, std::string> > values;
for(int i = 0; i < ArrSize; i++) {
std::pair<std::string, std::string> p =
std::make_pair(std::string(arr1[i]), std::string(arr2[i]));
values.push_back(p);
}
std::map<std::string, std::string> m(values.begin(), values.end());
Upvotes: 3
Reputation: 1371
for(int i = 0; i < ArrSize; i++) {
m.insert(pair<string, string>(arr1[i], arr2[i]));
}
Upvotes: 0
Reputation: 476980
The easiest way to write this:
std::map<std::string, std::string> m {
{ "key1", "value1" },
{ "key2", "value2" },
};
This requires your compiler to support initializer lists (a feature of C++11).
Upvotes: 5