我正在阅读斯坦福大学的教程,目前正在解决STL的任务。任务是编写一个函数,接受一个map
的电影名称及其排名。根据评论家的评论,这个功能应该返回一个带有前3部电影的set
容器。这是我的解决方案:
#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文档,但由于我是新手,因此无法理解问题的含义。拜托,请你提示我吗?
答案 0 :(得分:2)
本声明
critics.insert(films.begin()->second, films.end()->second);
无效。编译器将类型films.begin()->second
的参数films.end()->second
和std::string
视为一对迭代器,并尝试应用operator ++。当然这会导致错误。
您应该使用标准算法std::transform
和std::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