2014-09-28 48 views
0

我的问题是如何插入一些元素插入语法将元素插入多重映射<串,向量<对<string, int> >>

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

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

+1

用['的std :: make_pair'](HTTP://en.cppreference .com/w/cpp/utility/pair/make_pair)以避免键入和拼写错误的冗余类型信息。 – Csq 2014-09-28 12:43:59

+0

@Csq我添加了评论,我跳过所有std ::简化代码一点。无论如何感谢您的提示 – user3119781 2014-09-28 12:59:03

+0

不工作......怎么样?错误?警告?崩溃?不要让我们陷入悬念。 – 2014-09-28 13:06:41

回答

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。

+0

对不起,错误,显然它应该是对 >> – user3119781 2014-09-28 12:56:33

+0

谢谢,它现在正在工作。我必须检查我在哪里犯了一个错字,因为我在开始时尝试了非常类似的代码。谢谢你的时间。 – user3119781 2014-09-28 13:27:24

+0

@ user3119781很高兴我帮了忙!如果它解决了您的问题 – 2014-09-28 13:28:02

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} 
+0

std :: vector (1,{“A”,'A'}它应该没有这个1,因为我们正在存储字符串和int对,我已经尝试过但它不起作用(1表示第一个解决方案) – user3119781 2014-09-28 13:10:10

+0

@ user3119781所有的工作,试试它在www.ideone.com std :: vector的构造函数需要两个参数 – 2014-09-28 13:12:06

+0

嗯,我试图通过只复制你的代码到我的,它的工作:),我的道歉。我需要在我的代码中尝试一个错误,因为我试图将它调整为你的,但是我在构造函数中跳过了那个。你可以尝试解释额外的参数或发送Soome链接来阅读它,我认为,像往常一样,我们可以使用普通的初始化列表或类似的东西。 – user3119781 2014-09-28 13:22:56

相关问题