C++中的复杂向量

Mik*_*ite 0 c++ vector

我使用这个向量:vector<string, vector<int>>.我认为第一次迭代返回一个数组:

for (vector<string, vector<int>>::iterator it = sth.begin(); it != sth.end(); ++it) {
    // how do I get the string?
    // I tried (*it)[0], but that did not work
}
Run Code Online (Sandbox Code Playgroud)

另外,我怎么会push_back这个向量?传球vector<string, vector<int>()>()对我不起作用.谢谢

Cas*_*Cow 5

矢量需要:

  • 第一个模板参数是一个类型
  • 第二个可选参数是分配器

vector<int> 不是字符串的有效分配器.

假设您不想在这里使用地图,您可能需要:

vector< pair<string, vector<int> > > outerVec;
vector<int> vecInt1, vecInt2;
vecInt1.push_back( 1 );
vecInt1.push_back( 5 );
vecInt2.push_back( 147 );
outerVec.push_back( std::make_pair( std::string("Hello World"), vecInt1 ) );
outerVec.push_back( std::make_pair( std::string("Goodbye Cruel World"), vecInt2 ));
Run Code Online (Sandbox Code Playgroud)

如果我们输入dede的东西:

typedef std::vector<int> inner_vectype;
typedef std::pair< std::string, inner_vectype > pair_type;
typedef std::vector< std::pair > outer_vectype;
Run Code Online (Sandbox Code Playgroud)

现在迭代:

for( outer_vectype::const_iterator iter = outerVec.begin(), 
      iterEnd = outerVec.end();
     iter != iterEnd; ++iter )
{
    const pair_type & val = *iter;
    std::cout << val.first;
    for( inner_vectype::const_iterator inIter = val.second.begin(),
          inIterEnd = val.second.end(); inIter != inIterEnd; ++inIter )
    {
        std::cout << '\t' << *inIter;
    }
    std::cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)

应该希望输出如下内容:

Hello World    1    5
Goodbye Cruel World   147
Run Code Online (Sandbox Code Playgroud)