使用 STL VS13 c++ 时出现错误 c2675

error c2675 using STL VS13 c++

我一直在阅读斯坦福教程,目前正在解决 STL 上的任务。任务是编写一个函数,它接受带有电影名称及其排名的 map 。根据评论家的评论,此功能应该 return 一个 set 包含前 3 部电影的容器。这是我的解决方案:

#include <iostream>
#include <set>
#include <map>
#include <numeric>
#include <iterator>
#include <string>
using namespace std;

struct compare {
    bool operator() (const double& a, const double& b) const {
        return (a > b);
    }
};

set <string> list(map <double, string, compare>& films) {
    set <string> critics;
    map<double, string, compare> ::iterator it = films.begin();
    if (films.size() <= 3) {
        critics.insert(films.begin()->second, films.end()->second);
    }
    else { 
        for (int i = 0; i < 3; ++i, ++it){
            critics.insert(it->second);
        }
    };
    return critics;
}


int main() {
    map <double, string, compare> films;
    films[5.0] = "a";
    films[8.0] = "b";
    films[10.0] = "c";
    films[7.4] = "d";
    set <string> critics = list(films);
    copy(critics.begin(), critics.end(), ostream_iterator <string>(cout, " "));
    cin.get();
}

不幸的是,它不断抛出错误:

error C2675: unary '++' : 'std::string' does not define this operator or a conversion to a type acceptable to the predefined operator

我已阅读有关错误的 MSDN 文档,但由于我是新手,无法理解问题的含义。你能给我提示一下吗?

此声明

critics.insert(films.begin()->second, films.end()->second);

无效。编译器将 std::string 类型的参数 films.begin()->secondfilms.end()->second 视为一对迭代器,并尝试应用运算符 ++。当然这会导致错误。

您应该使用标准算法 std::transformstd::insert_iterator 将字符串从映射复制到集合。

这是一个展示方法的演示程序

#include <iostream>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>

int main() 
{
    std::map<double, std::string, std::greater<double>> m =
    {
        { 2.2, "B" }, { 1.1, "A" }, { 4.4, "D" }, { 5.5, "E" }, { 3.3, "C" }
    };

    for ( const auto &p : m )
    {
        std::cout << p.first << '\t' << p.second << std::endl;
    }

    std::set<std::string> s;

    std::transform( m.begin(), std::next( m.begin(), 3 ), 
                    std::inserter( s, s.end() ),
                    []( const auto &p ) { return p.second; } );

    for ( const auto &t : s ) std::cout << t << ' ';
    std::cout << std::endl;

    return 0;
}

程序输出为

5.5 E
4.4 D
3.3 C
2.2 B
1.1 A
C D E