c++ - C++ 中的复杂 vector

标签 c++ vector

我使用这个 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
}

此外,我将如何push_back到这个 vector ?路过vector<string, vector<int>()>()没有为我工作。谢谢

最佳答案

vector 需要:

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

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

假设您不想在此处使用 map ,您可能想要:

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

如果我们 typedef 东西:

typedef std::vector<int> inner_vectype;
typedef std::pair< std::string, inner_vectype > pair_type;
typedef std::vector< std::pair > outer_vectype;

现在迭代:

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

应该希望输出如下内容:

Hello World    1    5
Goodbye Cruel World   147

关于c++ - C++ 中的复杂 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5310601/

相关文章:

c++ - 设置标准 :cin to a string

c++ - 计算杆的最大总价,切割具有唯一长度值

c++ - CFileDialog 的当前目录在.exe 和.dll 中不一致

R中向量和矩阵之间的关系?

c++ - 相互依赖的 C++ 类,由 std::vector 持有

c++ - 如何将 vector 内容的 vector 放入单个列 vector 中

c++ - 从成对 vector 中的字符串中取出月份

c++ - 如何(手动)对齐 C/C++ 中的单元格?

c++ - 正则表达式,捕获 4 个数字。或行开始/结束

r - 使用 cbind 和 or 参数组合两个向量