如何解决地图,C ++中的矢量
错误:与“操作符”)
我想要相同的键和多个值,例如键是10的值是2,3,4 但是“ * iter”是错误的。 如何在C ++中绘制地图,矢量?
解决方法
在您的代码段中,表达式*iter
的值是类型std::pair<std::string,std::vector<int>>
的对象,未为其定义运算符
错误消息
error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and
‘std::pair<const std::__cxx11::basic_string,std::vector >’)
对此说。
最简单的方法是使用基于范围的for循环。
这是一个演示程序。
#include <iostream>
#include <string>
#include <vector>
#include <map>
int main()
{
std::map<std::string,std::vector<int>> m;
m["10"].assign( { 2,3,4 } );
for ( const auto &p : m )
{
std::cout << p.first << ": ";
for ( const auto &item : p.second )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
return 0;
}
程序输出为
10: 2 3 4
如果要使用迭代器编写普通的for循环,则循环可以采用以下方式。
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iterator>
int main()
{
std::map<std::string,4 } );
for ( auto outer_it = std::begin( m ); outer_it != std::end( m ); ++outer_it )
{
std::cout << outer_it->first << ": ";
for ( auto inner_it = std::begin( outer_it->second );
inner_it != std::end( outer_it->second );
++inner_it )
{
std::cout << *inner_it << ' ';
}
std::cout << '\n';
}
return 0;
}
再次显示程序输出是
10: 2 3 4
,
我建议使用结构化绑定和基于范围的for循环:
std::map<std::string,std::vector<int>> m;
for (auto&[str,vec] : m) { // bind str to "first" in the pair and vec to "second"
std::cout << str << ':';
for(auto lineno : vec) std::cout << ' ' << lineno;
std::cout << '\n';
}
,
您可以定义通过std::ostream
进行打印的方式,如下所示:
#include <iostream>
#include <map>
#include <vector>
#include <string>
// define how to print std::pair<std::string,std::vector<int>>
std::ostream& operator<<(std::ostream& stream,const std::pair<std::string,std::vector<int>>& pair) {
stream << "(" << pair.first << ",{";
bool first = true;
for (int e : pair.second) {
if (!first) stream << ",";
stream << e;
first = false;
}
stream << "})";
return stream;
}
int main(void) {
std::string yytext = "hoge";
int lineno = 42;
// below is copied from the question
std::map<std::string,std::vector<int>> m;
m[yytext].push_back(lineno);
std::map<std::string,std::vector<int>>::iterator iter;
for (iter=m.begin(); iter!=m.end(); iter++){
std::cout<<iter->first<<":"<<*iter<<std::endl;}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。