我读了一些与此问题相关的其他线程,但没有为我的问题提供解决方案.我希望你们能给我一些想法或建议.
我正在尝试实现这个名为的类Map.它应该包含2个迭代器 - iterator和const_iterator.
我实现了它们 - iterator继承自const_iterator,在Map类中我有以下功能:
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
Run Code Online (Sandbox Code Playgroud)
我们获得了一个示例文件,以了解实现所需的内容.在那里,有以下代码:
Map<std::string,int> msi;
Run Code Online (Sandbox Code Playgroud)
...
// print map
for(Map<std::string,int>::const_iterator it = msi.begin(); it != msi.end(); ++it) {
// more stuff here
}
Run Code Online (Sandbox Code Playgroud)
因为msi是一个非常量的Map实例,msi.begin()调用iterator begin()和不调用const_iterator begin() const,导致意外的行为.
假设示例文件没问题,我该怎么做才能msi.begin()调用正确的const_iterator函数?(考虑到它,迭代器,是类型const_iterator).
编辑:关于自动转换的讨论,我决定添加我的迭代器类,请指出我的错误.
class Map {
//...
public:
class const_iterator {
private:
Node* currNode;
public: …Run Code Online (Sandbox Code Playgroud) 我有这个代码,我发现将字符串切成单词.我无法弄清楚while部分是如何工作的.如何知道将没有空格的单词提取到buf变量?似乎提取运算符(>>)既用于将位进入缓冲区,又用于循环返回true - 我只是无法弄清楚它是如何通过空格来切割单词的.
string buf; // Have a buffer string
stringstream ss(str); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
Run Code Online (Sandbox Code Playgroud) 我有这个奇怪的问题-我定义并声明了函数,没有错别字,没有外部库,没有命名空间失败,没有模板,没有其他线程提及-但我仍然为函数调用得到“未定义符号”。
我有以下代码:
在一个.cpp文件中:
string print(const FanBookPost& post) {
std::stringstream ss;
// notice! post.getOwner.getId! owner needs to be fan
ss << post.getOwner().getId() << ": " << post.getContent() << "(" << post.getNumLikes()
<< " likes)";
return ss.str();
}
Run Code Online (Sandbox Code Playgroud)
该文件包含FanBookPost.h。
然后我在FanBookPost.h中:
class FanBookPost {
private:
Fan owner;
std::string content;
int numOfLikes;
int seqNum;
public:
// constructors
int getNumLikes();
std::string getContent();
Fan getOwner();
int getNumLikes() const;
std::string getContent() const;
Fan getOwner() const;
};
Run Code Online (Sandbox Code Playgroud)
如您所见,我准备了const和常规版本。在第一个.cpp文件中,“ post”函数获取的是const。
我在FanBookPost.cpp中在这里实现了这些功能:
class FanBookPost {
private:
Fan owner;
std::string content; …Run Code Online (Sandbox Code Playgroud)