将元素插入到multimap中的语法 >>

问题描述 投票:0回答:2

我的问题是如何将一些元素插入到表单的多图中

multimap<string, vector<pair<string, int>>> someMap; //std skipped to simplify

我尝试了不同的语法,我认为最接近的可能就是这个

someMap.insert(pair<string,vector<pair<string, int>>>(someString1, vector<pair<string, int>> { pair<string, int> (someString2, someInt) }));

不幸的是它不起作用。有小费吗??

c++ vector syntax multimap std-pair
2个回答
2
投票

第一对的类型是错误的

pair<string,vector<string, int>>
                   ^^^^^^^^^^^

无论如何我建议:

multimap<string, vector<pair<string, int>>> someMap;
vector<pair<string,int>> obj;
someMap.insert(make_pair("hello", obj));

或者如果你坚持使用那种语法(详细模式):

  multimap<string, vector<pair<string, int>>> someMap;
  string someString2 = "hello";
  string someString1 = "world";
  int someInt = 42;
  someMap.insert(pair<string,vector<pair<string, int>>>(someString1, vector<pair<string, int>> { pair<string, int> (someString2, someInt) }));

这需要C ++ 11。


1
投票

请尝试以下方法

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <utility>

int main() 
{
    typedef std::pair<std::string, int> value_type;
    std::multimap<std::string, std::vector<value_type>> m; 

    m.insert( { "A", std::vector<value_type>( 1, { "A", 'A' } ) } );

    return 0;
}

或者另一个例子

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <utility>

int main() 
{
    typedef std::pair<std::string, int> value_type;
    std::multimap<std::string, std::vector<value_type>> m; 

    auto it = m.insert( { "A", std::vector<value_type>( 1, { "A", 'A' } ) } );

    for ( char c = 'B'; c <= 'Z'; ++c )
    {
        const char s[] = { c, '\0' };

        it->second.push_back( { s, c } );
    }

    size_t i = 0;
    for ( const auto &p : it->second )
    {
        std::cout << "{" << p.first << ", " << p.second << "} ";
        if ( ++i % 7 == 0 ) std::cout << std::endl;
    }
    std::cout << std::endl;

    return 0;
}

输出是

{A, 65} {B, 66} {C, 67} {D, 68} {E, 69} {F, 70} {G, 71} 
{H, 72} {I, 73} {J, 74} {K, 75} {L, 76} {M, 77} {N, 78} 
{O, 79} {P, 80} {Q, 81} {R, 82} {S, 83} {T, 84} {U, 85} 
{V, 86} {W, 87} {X, 88} {Y, 89} {Z, 90} 
© www.soinside.com 2019 - 2024. All rights reserved.