簡體   English   中英

int和矢量地圖 <int> 在c ++中

[英]Map of int and vector<int> in c++

我一直在使用<map> ,我將地圖聲明為

map <int , vector<int> > tree;

我正在嘗試為它賦值。 我的目標是將多個值作為其鍵的元素。 像這樣的東西:

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

我試圖像這樣分配到地圖但它不起作用。

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

你能弄清楚問題出在哪里,或者我如何創建一個兼容Python字典的函數?

編輯: tree[1]=vector<int>(0); tree[2]=vector<int>(1,0); tree[1]=vector<int>(0); tree[2]=vector<int>(1,0); 以上兩種分配工作方式。

編輯2:我沒有使用c++11

使用C ++ 11,您可以嘗試:

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

除此之外,這個問題可以使用更多的細節和一些你已經嘗試過的代碼......

既然你要求C ++ 03答案,那么(比C ++ 11更詳細)解決方案將起作用。

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

你考慮過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));
}

正如Daniel Frey指出的那樣,你可以使用

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

在類似python的偽代碼中,這里使用的向量構造函數是

def vector(arr)

原帖建議您嘗試使用表單的構造函數

def vector(*args)

哪個不存在。

如果您不使用C ++ 11,請考慮使用vector其他構造函數之一

沒有C ++ 11,代碼就不那么優雅了:

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);

我並不特別喜歡 va_args,但只要你(用戶)不搞亂它,即混合類型,解決方案就會比大多數人更“整潔”。 另一個缺點是你的向量不能包含-1,但是你的示例沒有顯示它。

#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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM