rel1x
rel1x

Reputation: 2441

How to get value from map by key

How I can get value from map by key? I have a vector of ints A, and I have a map. I want to print M[1], but I don't understand how I can do it, because I've got an error:

error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'mapped_type' (aka 'std::__1::pair<int, int>'))
    cout << M[1];
    ~~~~ ^  ~~~~

My code:

int main() {
    vector<int> A;
    map<int, pair<int,int> > M;

    FOR(i,1,maxN) {
        pair<int,int> p;

        p.first = 1;
        p.second = 2;

        M[i] = p;
    }

    FOR(i,0,t) {
        int x = A[i];
        cout << M[x] << endl;
    }

    return 0;
}

Upvotes: 1

Views: 489

Answers (2)

Zan Lynx
Zan Lynx

Reputation: 54393

Paani has a good answer. I thought I would post mine, which is the same idea but slightly different.

Instead of printing the values from the pair you can create an ostream function to print any pair.

Like this:

#include <iostream>
#include <utility>

template<class T, class U>
std::ostream& operator<<(std::ostream &os, const std::pair<T, U> &p) {
    os << '{' << p.first << ',' << p.second << '}';
    return os;
}

int main() {
    std::pair<int, int> p(7, 11);
    std::pair<std::string, double> q("My Double", 37.02);

    std::cout << p << std::endl;
    std::cout << q << std::endl;
    return 0;
}

Upvotes: 2

Paani
Paani

Reputation: 560

Value type of the map is a std::pair. You need to individually print the 2 values in the pair:

cout<< M[x].first << "," << M[x].second << endl;

Upvotes: 4

Related Questions