首页 > 解决方案 > 集合的 C++ 嵌套迭代器

问题描述

我正在尝试对集合使用嵌套迭代器,如下所示,但出现错误:

错误:'operator+' 不匹配(操作数类型是 'std::_Rb_tree_const_iterator' 和 'int')for(auto itj = iti+1; itj != st.end(); itj++){

int alternate(string s) {
    set<char> st;
    for(char x : s){
        st.insert(x);
    }

    for(auto iti = st.begin(); iti != st.end(); iti++){
        //string t = "";
        for(auto itj = iti+1; itj != st.end(); itj++){
            cout<<*iti<<" "<<*itj<<endl;
        }
    }
}

标签: c++loopsiteratorset

解决方案


std::set的迭代器不满足指定的要求LegacyRandomAccessIterator。它只满足LegacyBidirectionalIterator.

所以iti + 1不是一个有效的表达式,迭代器没有匹配的 operator+。

要解决您的问题,您可以使用std::next.

for (auto iti = st.begin(); iti != st.end(); ++iti){
    for (auto itj = std::next(iti); itj != st.end(); ++itj){
        cout << *iti << " " << *itj << endl;
    }
}

这是一个演示


推荐阅读