[英]inserting in a vector of vector string from vector vector of vector pair<int,string>
vector<vector<pair<int,string>>> v(mxfreq+1);
for(it=m.begin();it!=m.end();it++)
{
v[it->second.second].push_back(make_pair(it->second.first,it->first));
}
vector<vector<string>> v1;
for(int i=mxfreq;i>=0;i--)
{
string t=to_string(i);
if(v[i].size()>1)
{
sort(v.begin(),v.end());
}
for(int j=0;j<v[i].size();j++)
{
v1.push_back(v[i][j].second);
v1.push_back(t);
}
}
//cout<<v[0][0].first<<endl;
return v1;
在這里,我試圖將它從向量 pair<int,string> 的向量插入到向量字符串的向量中,但我收到錯誤v1.push_back(v[i][j].second); 這里我們可以假設mxfreq是一個大於 0 的整數
要使用相互嵌套的基於范圍的for
循環來實現“簡單”解決方案,可以執行以下操作:
// Make sure the destination vector have enough memory allocated
v1.reserve(v.size());
for (auto const& v_pairs : v)
{
// Create a temporary vector for the string
std::vector<std::string> v_strings;
// And make sure it have enough memory allocated
v_strings.reserve(v_pairs.size());
// Copy the string from each pair into the string vector
for (auto const& pair : v_pairs)
{
v_strings.emplace_back(pair.second);
}
// And move the string vector into the destination vector
v1.emplace_back(std::move(v_strings));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.