迭代字符串集时没有可行的转换

No viable conversion when iterating over string set

本文关键字:转换 字符串 迭代      更新时间:2023-10-16

给定集合:

{"警报", "警报", "问题"}

我想要输出:

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'

代码的问题在于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.


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

auto相当于std::string&.