optimus203
optimus203

Reputation: 108

Associative Array with Vector in C++

I need to implement my map with a vector. My map is layed out like:

map<strong,double> mapName;

I need to convert over to vector so that I can do a linear search through the elements.

Thanks in advance for the time.

Upvotes: 0

Views: 2702

Answers (2)

Andr&#233; Caron
Andr&#233; Caron

Reputation: 45274

You can easily convert to a vector using vector's range constructor like so:

 map<string,double> item_map;
 // ... populate item map ...

 // copy elements to a vector.
 vector< pair<string,double> > item_vector(item_map.begin(), item_map.end());

However, if you only need to do a linear search, you don't need to copy the elements. Just iterator over the items like so:

 typedef map<string,double>::iterator iterator;
 iterator current = item_map.begin();
 const iterator end = item_map.end();
 for (; current != end; ++current) {
     // current->first is the 'string' part.
     // current->second is the 'double' part.
 }

Upvotes: 1

Adam Miller
Adam Miller

Reputation: 1783

You don't have to convert to vector to do a linear search. You can use C++ iterators to grab the beginning of a map and the end, then access the key and value with first and second.

See this

For example:

for (map<strong, double>::iterator ii = mapName.begin(); 
    ii!=mapName.end();ii++) {
      cout << ii->first << endl;  //returns a key
      cou << ii->second << endl; //returns ii->first's current corresponding value.
}

Upvotes: 0

Related Questions