对 2D 向量内的向量进行排序
我在二维向量中排序向量时遇到问题?我想根据它们的容量从最大到最小对它们进行排序。
示例:ROWS {{1,2,3},{1,2},{1,2,3,4,5}}
应按 ROWS.capacity() 排序; // ROWS {{1,2,3,4,5},{1,2,3},{1,2}}
以下是我到目前为止所做的代码的一部分:
std::vector< std::vector<int> >::iterator row;
std::vector<int>::iterator col;
for (row=ROWS.begin(); row<ROWS.end(); row++){
Logger::logln(LOG_DEBUG, "ROW: %d",row->capacity());
for (col = row->begin(); col != row->end(); col++){
Logger::logln(LOG_DEBUG, " CONTENT: %d ",*col);
}
}
我需要执行以下操作: if(行1.容量>行2.容量) 然后交换或者类似的东西。
提前致谢 :)
I have a problem sorting vectors in 2D vector? I would like to sort them based on their capacity from the largest to the smallest.
Example: ROWS {{1,2,3},{1,2},{1,2,3,4,5}}
it should be sorted as ROWS.capacity(); // ROWS {{1,2,3,4,5},{1,2,3},{1,2}}
The following is part of the code i did until now:
std::vector< std::vector<int> >::iterator row;
std::vector<int>::iterator col;
for (row=ROWS.begin(); row<ROWS.end(); row++){
Logger::logln(LOG_DEBUG, "ROW: %d",row->capacity());
for (col = row->begin(); col != row->end(); col++){
Logger::logln(LOG_DEBUG, " CONTENT: %d ",*col);
}
}
i need to the following:
if(row1.capacity > row2.capacity)
then swap or something like this.
Thanks in advance :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将
std::sort
与自定义排序谓词一起使用:如果
std::sort
在内部使用std::swap
,这应该可以很好地工作,否则,复制行的成本可能会非常昂贵,并且您可能需要实现自己的排序功能。您还应该考虑,您是否真的需要
capacity()
而不是size()
。You could use
std::sort
with a custom ordering predicate:This should work well if
std::sort
usesstd::swap
internally, otherwise the copying of rows could get quite expensive and you probably need to implement your own sorting function.You should also think, if you really need
capacity()
and notsize()
.将 std::sort 与自定义比较函数一起使用,如下所示:
我使用
size()
在这里,但如果您确实需要capacity()
,只需在比较函数中更改它即可。Use std::sort with custom comparison function, like this:
I used
size()
here, but if you really needcapacity()
simply change it in comparison function.