【发布时间】:2014-11-06 06:29:38
【问题描述】:
您好,这是我的第一篇文章 :)
我对 C++ 编程非常陌生,并不完全理解字符串引用和指针的实现。我花了一个多小时在网上搜索,以了解如何将这两个字符串中的一个转换为“可比较的”,但我发现的所有内容都与比较两个普通字符串或一个 const string& 和一个char*,或稍有不同的东西。 我已经阅读了字符串维基百科以及我想尝试解决这个问题的所有内容,但我根本不知道发生了什么。
简而言之,我需要使用 '
我从“http://www.cplusplus.com/reference/string/string/operators/”理解它的方式 运算符的左侧和右侧都必须是 const string&
bool operator< (const string& lhs, const string& rhs);
bool operator< (const char* lhs, const string& rhs);
bool operator< (const string& lhs, const char* rhs);
在我的代码中,我有一个已经是 const string& 的字符串值,以及一个是 string* 的字符串值。
问题是,当我尝试将 const string& 与 string* 进行比较时,出现错误。
我是新手,几乎不了解 const string& 是什么,以及为什么我不能将它与 string* 进行比较。
您能帮我找到一种方法来比较这两个字符串以进行 BST 插入吗?
这是我的 BST 课程
class BST
{
public:
BST();
~BST();
void insertContent(const string& word, const string& definition);
void deleteContent(string* word);
const string* getContent(const string& word);
private:
class Node
{
public:
Node(string* word, string* definition)
{left=NULL; right=NULL; m_word=word; m_definition=definition;}
Node* left;
Node* right;
string* m_word;
string* m_definition;
};
这是我需要帮助比较字符串的插入函数
void BST::insertContent(const string& word, const string& definition)
{
Node* ptr = root;
//Node* entry = new Node(word, definition);
if (root == NULL)
{
root = new Node(word, definition);
return;
}
while (ptr != NULL)
{
const string& curwor = ptr->m_word; /*I was thinking of making my own const string& out of ptr->m_word but it didn't work. */
**if (word < ptr->m_word)**
{
}
}
}
【问题讨论】:
-
'const' 代表常数。如果您声明为“const”,则无法修改。如果你可以改变它的值,那一定是一个变量。
-
取消引用指针:
if (word < *(ptr->m_word))。你可以用五行代码问这个问题。 -
您可以使用 '==' 或 '!=' 比较两个字符串是否相等。您最好不要使用其他运算符,而是使用“比较”方法。
-
字符串只是 char[] 的抽象。其实c++只是给了你一个string类型和方便的函数来操作它,但在幕后,它只是被当作一个char数组来处理。因此,您仍然可以像使用 char[] 一样使用指针来解析字符串。
标签: c++ string pointers reference compare