2015-04-02 93 views
1

我正在閱讀斯坦福大學的教程,目前正在STL上解決任務。其任務是編寫一個函數,該函數接受帶有電影名稱和排名的map。根據評論家的評論,這個功能應該會返回set容器與前3部電影。這裏是我的解決方案:錯誤c2675使用STL VS13 C++

#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文檔上的錯誤,但因爲我是新來這個無法理解的意思問題。請問,你能提醒我一下嗎?

回答

2

本聲明

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

是無效的。編譯器將std::string類型的參數films.begin()->secondfilms.end()->second視爲一對迭代器,並嘗試應用operator ++。當然這會導致錯誤。

您應該使用標準算法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 
+0

喜維拉德。 – 2015-04-02 17:49:56

+0

@Lightning Racis在OBRIT僑。來吧? – 2015-04-02 17:53:23

+0

Bine,mulţumesc。 Şidumneavoastră? – 2015-04-02 17:57:40