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