2011-06-04 184 views
1

在2D矢量中排序矢量时出现问题?我想根据他们从最大到最小的能力对他们进行分类。在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); 
    } 
} 

我需要以下内容: 如果(row1.capacity> row2.capacity) 然后交换或类似的东西。

感谢提前:)

+1

你确定要“容量”而不是“尺寸”吗? – 2011-06-04 15:06:43

+1

行数? 2D矢量?你知道,你的矢量只是矢量的矢量。矢量的大小是它包含的元素的数量。 'ROWS.size()'是上下文中的行数,'ROWS [0] .size()'是第一行的长度。 “容量”意味着不同的东西。这是可以添加到矢量的元素的数量,直到它需要重新分配其内部存储为止。所以我认为“尺寸”应该是你选择的方法。 – 2011-06-04 15:18:54

回答

1

你可以使用std::sort使用自定义排序谓语:

struct CapacityGreater : public std::binary_function<std::vector<int>, 
                std::vector<int>,bool> 
{ 
    bool operator()(const std::vector<int> &a, const std::vector<int> &b) const 
     { return a.capacity() > b.capacity(); } 
}; 

std::sort(ROWS.begin(), ROWS.end(), CapacityGreater()); 

这应该很好地工作,如果std::sort使用std::swap内部,否则行的复制可以得到相当昂贵的,你可能需要实现自己的排序功能。

你也应该想,如果你真的需要capacity()而不是size()

0

使用std::sort自定义比较函数,就像这样:

#include <vector> 
#include <algorithm> 

bool compare(const std::vector<int>& a, const std::vector<int>& b) 
{ 
    return a.size() > b.size(); 
} 

int main() 
{ 
    std::vector< std::vector<int> > v; 
    // populate your vector with values here 
    sort(v.begin(), v.end(), compare); 
    return 0; 
} 

我用size()在这里,但如果你真的需要capacity()简单地改变它的比较功能。

+0

好!我使用这种方法,但有一个问题:错误时调用排序? 错误:没有匹配函数调用'sort(__ gnu_cxx :: __ normal_iterator > *,std :: vector >,std :: allocator >>>,__gnu_cxx :: _ normal_iterator > *,std :: vector >,std :: allocator >>>>,<未解析的重载函数类型>)' – NIX 2011-06-04 15:55:45

+0

@PRINCE请发布一个代码它调用sort()。 – 2011-06-04 16:07:10