底线是我正在为一个结构编写一个方法,它添加到作为结构一部分的 map 。
在头文件中,对于结构,map 变量被声明为 map(string,Node)(Node 是另一个结构)(它在代码中使用 '>',它只是在这个文本编辑器中那些不出现。)
Network 有一个方法,它接受一个 ifstream,并使用 getline 等方法获取每行中的数据并创建一个节点,该节点被添加到 Network 变量的映射中。
在头文件中,此映射称为“节点”。所以在该方法的代码中,我有 nodes.insert(string-variable,node-variable)。我得到一个关于树的错误。
error C2664: 'std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const _Kty,_Ty>>>> std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const _Kty,_Ty>>>>,const std::pair<const _Kty,_Ty> &)': cannot convert argument 1 from 'std::string' to 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const _Kty,_Ty>>>>'
在 functions.h 中,“网络”:
struct Network{
string label;
map<string, Node> nodes;
vector<string> route;
Network()=default;
Network(ifstream &);
string to_string () const;
Node get_node(string);
void put_node(Node);
bool in_route(const Node&);
Node closest(Node &);
string calculate_route(const Node&, const Node&);};
'Node' 是它自己的结构,(int, int, string),编码在 Network 之上;让我知道我是否也应该包括它的代码。
现在在 functions.cpp 中,我正在编写 ifstream 构造函数的代码。我有
Network::Network(ifstream &file) {
string line;
Node temp;
while (getline(file, line)) {
stuff I know works at creating a node (int, int, string);
nodes.insert(temp.label, temp);
}
}
因此,我尝试添加到 map(string,Node) 中,当我尝试使用字符串节点对时,它说它无法从字符串转换为带有 _Tree 的内容。
我在 Visual Studio 2015 中。
如果需要,我可以包含更多代码,我只是不想让它变得比必要的更困惑。
最佳答案
查看 map<K,V>::insert()
的文档.所有带有两个参数的重载都将迭代器作为第一个参数,而不是 string
。 .这就是您的编译器所提示的,因为它正在尝试并未能转换 string
到一个迭代器。
你的意思似乎是
nodes.insert(std::make_pair(temp.label, temp));
关于C++映射错误,有结构和方法,无法将字符串转换为_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43033443/