gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:54:40 25 4
gpt4 key购买 nike

我一直在阅读斯坦福教程,目前正在解决 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 文档,但由于我是新手,无法理解问题的含义。你能给我提示一下吗?

最佳答案

这个声明

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

关于c++ - 使用 STL VS13 c++ 时出现错误 c2675,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29418743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com