Complex vectors in C++
开发者_开发技巧I work with this vector: vector<string, vector<int>>
.
I supposed that the first iteration returns an array:
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
}
Also, how would I push_back
to this vector? Passing vector<string, vector<int>()>()
did not work for me. Thanks
vector takes:
- first template parameter is a type
- second optional parameter is an allocator
vector<int>
is not a valid allocator for string.
Assuming you do not want map here, you probably want:
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 ));
If we typedef things:
typedef std::vector<int> inner_vectype;
typedef std::pair< std::string, inner_vectype > pair_type;
typedef std::vector< std::pair > outer_vectype;
Now iterate:
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';
}
Should hopefully output something like:
Hello World 1 5
Goodbye Cruel World 147
精彩评论