遍历字符串集时没有可行的转换

时间:2018-10-22 23:33:18

标签: c++

给出集合:

{“警报”,“警报”,“问题”}

我想要输出:

alarm
alert
issue

我想向后或向前打印集合中的每个元素。以下是我尝试过的代码:

set<string> str_set = {"hi", "bye", "there"}; string cur_word;

for(long iter = str_set.begin(); iter!= set.end(); iter++) {
    cout << iter << endl;
}

我遇到了错误:

No viable conversion from 'std::__1::set<std::__1::basic_string<char>,
   std::__1::less<std::__1::basic_string<char> >, 
std::__1::allocator<std::__1::basic_string<char> > >::iterator' (aka 
'__tree_const_iterator<std::__1::basic_string<char>, 
std::__1::__tree_node<std::__1::basic_string<char>, void *> *, long>') to 
'long'

1 个答案:

答案 0 :(得分:1)

您的代码存在问题,就是std::set<std::string>::begin()返回的迭代器被转换为long时间。 您应该将iter的类型定义为std::set<std::string>::iteratorauto


std::set<std::string> str_set = {"hi", "bye", "there"};
for(auto iter = str_set.begin(); iter != str_set.end(); iter++) {
    std::cout << *iter << '\n';
}

auto等同于std::set<std::string>::iterator


OR

std::set<std::string> str_set = {"hi", "bye", "there"};
for(auto &value : str_set) {
    std::cout << value << '\n';
}

auto等同于std::string&