1

what is the easiest way to print out a vector of strings on the console?

I got something like this

map < int, vector<string>>

and i want to print the values to a user-given key.

typemap::iterator p1;

cin >> i
for (pointer = map.begin(); pointer != map.end(); ++pointer)
{
if ((pointer->first) == i)
{
//The program should print the values right here.
}
}
Sid
  • 2,683
  • 18
  • 22
Eppok
  • 55
  • 1
  • 7
  • 1
    Don't use a `for` loop to search a `map`, use [map::find](http://www.cplusplus.com/reference/map/map/find/). The whole point of a `map` is to make lookup by key efficient. – David Schwartz May 07 '15 at 17:04
  • Also: Look up the documentation for std::map (eg.: http://en.cppreference.com/w/cpp/container/map). Or get a book: http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list –  May 07 '15 at 17:09

2 Answers2

2

With a loop. And don't iterate through a map to find a key.

auto found = map.find(i);
if (found != map.end()) {
    for (string const & s : found->second) {
        cout << s << ' ';
    }
}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

You may use std::ostream_iterator

#include <algorithm>
#include <iterator>
/* .... */
auto found = map.find(i);
if (found != map.end()) {
    std::copy(found->second.begin(), 
              found->second.end(),
              std::ostream_iterator<std::string>(std::cout," "));
}

More information here: http://www.cplusplus.com/reference/iterator/ostream_iterator/

ivaigult
  • 6,198
  • 5
  • 38
  • 66