我正在处理我大学的cpp课程,我遇到了一个我自己无法解决的问题。 main.cpp由讲师给出,你必须使头文件工作。在那一个
Tedge &operator()(const Tnode &first, const Tnode &sec)
函数应该返回要覆盖的Tedge,但我得到了一个
error: binding 'const std::__cxx11::basic_string<char>' to reference of type 'std::__cxx11::basic_string<char>&' discards qualifiers
错误。当没有什么是常数时,为什么会发生这种情况,我该如何解决呢?当我删除&amp;在operator()运行之前,程序无法设置变量的值。
哦,我们需要在C ++ 98中编程。
的main.cpp
#include "lgraph.h"
#include <iostream>
#include <string>
int main()
{
int yourMark = 1;
LGraph<int, std::string, true> dg;
dg.add(1);
dg.add(2);
dg.add(3);
dg.add(8);
dg.add(2,1, "Baker street");
dg.add(1, 3, "Big street");
dg.add(2, 3, "Small street");
dg.add(8, 3, "Dog street");
const LGraph<int, std::string, true> cdg = dg;
LGraph<char, std::string, false> ug;
ug.add('A');
ug.add('G');
ug.add('H');
ug.add('A', 'H', "Stackoverflow street");
yourMark += cdg.is_directed() + ug.is_directed();
if(!cdg.has("Nowheretobefound") && "Big street" == cdg(1,3)){
yourMark = ug.countNodes();
}
dg(2, 3) = "Flower street";
std::cout<<dg(2,3) << std::endl;
if(4 == cdg.countEdges() && !dg.has("Small street")) {
dg.remove(1);
yourMark = ug.countEdges() + dg.countNodes();
}
std::cout << "Your mark is " << yourMark << std::endl;
return 0;
}
lgraph.h
#ifndef LGRAPH_H_INCLUDED
#define LGRAPH_H_INCLUDED
#include <vector>
#include <iostream>
#include <map>
template<typename Tnode, typename Tedge, bool isDir>
class LGraph {
typename std::vector<Tnode> nodes;
typename std::map<Tedge, std::pair<Tnode, Tnode>> edges;
bool isdir;
public:
LGraph():isdir(isDir){};
void add(Tnode value) {
nodes.push_back(value);
}
void add(Tnode n, Tnode n2, Tedge e) {
edges.insert(std::pair<Tedge, std::pair<Tnode, Tnode>>(e, std::pair<Tnode, Tnode>(n, n2)));
}
bool is_directed() const{
return isdir;
}
bool has(Tedge edge) const{
bool l = false;
for(typename std::map<Tedge, std::pair<Tnode, Tnode>>::const_iterator it = edges.begin(); it != edges.end() && !l; it++) {
l = it -> first == edge;
}
return l;
}
int countNodes() {
return nodes.size();
}
const Tedge operator()(const Tnode &first, const Tnode &sec) const {
for(typename std::map<Tedge, std::pair<Tnode, Tnode>>::const_iterator it = edges.begin(); it != edges.end(); it++) {
if(it->second.first == first && it->second.second == sec) {
return it->first;
}
}
return nullptr;
}
Tedge &operator()(const Tnode &first, const Tnode &sec){
for(typename std::map<Tedge, std::pair<Tnode, Tnode>>::iterator it = edges.begin(); it != edges.end(); it++) {
if(it->second.first == first && it->second.second == sec) {
return it->first;
}
}
}
const int countEdges() const {
return edges.size();
}
void remove(const Tnode &node) {
for(int i = 0; i < nodes.size(); i++) {
if(nodes[i] == node) {
int currentSize = nodes.size();
nodes.erase(nodes.begin() + i);
nodes.resize(currentSize-1);
}
}
}
};
#endif // LGRAPH_H_INCLUDED