字符串与指针比较的问题

时间:2014-06-02 21:09:24

标签: c++ list iterator

我有三个列表,我想实现搜索功能。

代码如何工作是我创建一个从每个列表的开头开始的迭代器,它将用户输入的内容与列表中的每个值进行比较,当它找到匹配时,它应该增加一个整数变量一个,所以最后会说:

  

your value is found: <x amount of times in Example list>

我遇到的问题是它编译得很好,但最终结果仍然给出了0,就像它没有增加变量一样。

我想知道是否在比较迭代器指向用户输入的值时遇到问题,有人可以对此有所了解吗?用于

中的测试目的

在迭代器search_disregard上我手动将4个相同的值放在列表中,所以我知道最终结果应该显示4,但我仍然得到0:

cout << "\nSearch for: ";
string edit_search;
cin >> edit_search;

list<string>::iterator search_disregard = disregard_list.begin();
list<string>::iterator search_compare   = compare_list.begin();
int search_disregard_count = 0;
int search_compare_count   = 0;


for (int x = 0; x < disregard_list.size(); ++x)
{
    if (*search_disregard == edit_search)
    {
        ++search_disregard_count;
    }
}

for (int x = 0; x < compare_list.size(); ++x)
{
    if (*search_compare == edit_search)
    {
        ++search_compare_count;
    }
}

cout << edit_tag << edit_search << " is found in the following: \n" << endl;
cout << search_disregard_count << " time(s) in the Disregard List" << endl;
cout << search_compare_count << " time(s) in the Compare List" << endl;

buffer_clear();

1 个答案:

答案 0 :(得分:3)

你永远不会增加你的迭代器,所以它们总是指向第一个元素。惯用的方式:

for(auto it = container.begin(); it != container.end(); ++it) ...