【问题标题】:Beginner C++ - String Comparison初学者 C++ - 字符串比较
【发布时间】:2014-02-26 15:14:53
【问题描述】:

我是一名 C# 程序员,最近想深入研究一些较低级别的东西,所以上周开始学习 C++,但偶然发现了一些我认为相当简单的东西。

我在我的程序中输入以下字符串:

"this is a test this test" 并且期望 wordStructList 包含 4 个单词的列表,其中 "test" 和 "this" 的出现次数设置为 2。然而,在调试时,字符串比较(我试过.compare 和 ==) 似乎总是增加出现的值,无论比较是否为真。

例如当前名称 = “是” word = "这个"

但出现次数仍在增加。

#include "stdafx.h"

using std::string;
using std::vector;
using std::find;
using std::distance;

struct Word
{
    string name;
    int occurrences;
};

struct find_word : std::unary_function<Word, bool> 
{
    string name;
    find_word(string name):name(name) { }
    bool operator()(Word const& w) const 
    {
        return w.name == name;
    }
};

Word GetWordStruct(string name)
{
    Word word;

    word.name = name;
    word.occurrences = 1;

    return word;
}

int main(int argc, char argv[])
{
string s;
string delimiter = " ";
vector<string> wordStringList;

getline(std::cin, s);

do
{
    wordStringList.push_back(s.substr(0, s.find(delimiter)));
    s.erase(0, s.find(delimiter) + delimiter.length());

    if (s.find(delimiter) == -1)
    {
        wordStringList.push_back(s);
        s = "";
    }

} while (s != "");

vector<Word> wordStructList;

for (int i = 0; i < wordStringList.size(); i++)
{
    Word newWord;

    vector<Word>::iterator it = find_if(wordStructList.begin(), wordStructList.end(), find_word(wordStringList[i]));

    if (it == wordStructList.end())
        wordStructList.push_back(GetWordStruct(wordStringList[i]));
    else
    {
        string word(wordStringList[i]);

        for (vector<Word>::size_type j = 0; j != wordStructList.size(); ++j)
        {
            string currentName = wordStructList[j].name;

            if(currentName.compare(word) == 0);
                wordStructList[j].occurrences++;
        }
    }
}

return 0;
}

我希望这个问题是有意义的。有人对此有所了解吗?我也愿意接受有关如何使代码更明智/可读的任何提示。谢谢

【问题讨论】:

  • 您已经使用std::find_if。也可以使用std::count

标签: c++ string string-comparison


【解决方案1】:

问题在于if 语句后面的分号:

if(currentName.compare(word) == 0);

分号结束语句,所以下一行

wordStructList[j].occurrences++;

不再是if 语句的一部分,并且将始终被执行。

【讨论】:

  • 也不需要使用 if(currentName.compare(word) == 0) 只需执行 if(currentName == word)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 2016-02-08
  • 2013-11-22
相关资源
最近更新 更多