gpt4 book ai didi

C++从 map 创建排序 vector

转载 作者:太空狗 更新时间:2023-10-29 21:42:58 25 4
gpt4 key购买 nike

我正在尝试从 map 创建一个排序的 vector,根据不是 map 键的值排序。 map 值是block对象,我希望 vector 根据sizeblock的属性进行排序。
我的代码:

#include <map>
#include <string>
#include <vector>

struct block {
string data;
int size;
};

struct vecotrCompare {
bool operator()(pair<const string, block*> &left,
pair<const string, block*> &right) {
return left.second -> size < right.second -> size;
}
};

int main() {
map<const string, block*> myMap;
vector<pair<const string, block*> > myVector(
myMap.begin(), myMap.end());
sort(myVector.begin(), myVector.end(), vecotrCompare());
}

sort(...) 行无法编译,我遇到编译错误:

error: no match for call to ‘(vecotrCompare) (std::pair<const
std::basic_string<char>, block*>&, const std::pair<const
std::basic_string<char>, block*>&)’

最佳答案

vector 中的元素需要 MoveAssignable 或 CopyAssignable。 pair<const string, block*>都不是因为 const string .将其更改为 string并且您的代码可以编译。

map<string, block*> myMap;
vector<pair<string, block*> > myVector(myMap.begin(), myMap.end());

同时更改比较器,使参数类型为 const&

struct vecotrCompare {
bool operator()(pair< string, block*> const&left,
pair< string, block*> const&right) const {
return left.second -> size < right.second -> size;
}
};

Live demo


第二部分关于参数需要是 const&实际上不是必需的。来自§25.1/9

The BinaryPredicate parameter is used whenever an algorithm expects a function object that when applied to the result of dereferencing two corresponding iterators or to dereferencing an iterator and type T when T is part of the signature returns a value testable as true. In other words, if an algorithm takes BinaryPredicate binary_pred as its argument and first1 and first2 as its iterator arguments, it should work correctly in the construct binary_pred(*first1, *first2) contextually converted to bool (Clause 4). BinaryPredicate always takes the first iterator’s value_type as its first argument, that is, in those cases when T value is part of the signature, it should work correctly in the construct binary_pred(*first1, value) contextually converted to bool (Clause 4). binary_pred shall not apply any non-constant function through the dereferenced iterators.

所以标准从来没有提到仿函数的参数类型必须 const& , 但 libstdc++ 似乎将临时对象传递给仿函数和代码 doesn't compile除非你添加 const& (看起来这已在 gcc-4.9 中修复)。

另一方面,libc++ 和 VS2013 handle the case其中参数不是 const&正确。

关于C++从 map 创建排序 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24072180/

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