简体   繁体   中英

Map of int and vector<int> in c++

I have been working with <map> , where I declared a map as

map <int , vector<int> > tree;

and I am trying to assign values to it. My goal is to place multiple values as elements of its keys. Something like this:

0=null
1=>0
2=>1,0
3=>2,1,0
4=>3,2,1,0
5=>0

I tried to assign to the map like this but it does not work.

tree[3]=vector<int>(2,1,0);

Can you figure out where the problem is, or how can I make a function that works as a Python dictionary?

EDIT: tree[1]=vector<int>(0); tree[2]=vector<int>(1,0); tree[1]=vector<int>(0); tree[2]=vector<int>(1,0); the above 2 ways of assigning work.

EDIT2: I am not using c++11

With C++11, you could try:

tree[3]=vector<int>({2,1,0});

Other than that, the question could use more details and some code of what you already tried...

Since you are asking for a C++03 answer, this (more verbose than C++11) solution will work.

tree[3].push_back(2);
tree[3].push_back(1);
tree[3].push_back(0);

Have you considered std::multi_map ?

#include <map>

int main()
{
    std::multimap<int, int> map;

    for (int i=1; i < 6; i++)
        for (int j=1; j < i; j++)
            map.insert(std::make_pair(i, j));
}

As Daniel Frey points out, you can use

tree[3] = vector<int>({2,1,0})

In python-like pseudo-code, the vector constructor being used here is

def vector(arr)

The original post suggests you're trying to use a constructor of the form

def vector(*args)

which doesn't exist.

If you're not using C++11, consider using one of vector 's other constructors .

Without C++11, the code won't be as elegant:

tree[0]; // create empty vector for index 0
tree[1].push_back(0);
tree[2].push_back(1);
tree[2].push_back(0);
tree[3].push_back(2);
tree[3].push_back(1);
tree[3].push_back(0);
tree[4].push_back(3);
tree[4].push_back(2);
tree[4].push_back(1);
tree[4].push_back(0);
tree[5].push_back(0);

I don't particularly like va_args but the solution is "neater" to a degree than most as long as you (the user) don't mess it up, ie mixing types. Another downside is that your vector cannot contain -1, but your example case doesn't show it.

#include <vector>
#include <cstdarg>
#include <iostream>

//Unsafe but it works.
template<typename T>
std::vector<T> make_vector(T num, ...) {
    std::vector<T> result;
    va_list args;
    va_start(args,num);
    for(T i = num; i != -1; i = va_arg(args,T))
        result.push_back(i);
    va_end(args);
    return result;
}

int main() {
    std::vector<int> v = make_vector(0,1,2,3,-1); //-1 to stop
    //do stuff with vector v
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM