简体   繁体   中英

Sorting a vector of objects with std::sort()

I have the following struct:

struct Invariant
{
public:
    Invariant(int d, int dc)
    : Dim(d), DimCoupl(dc) {}
    void addTerm(int coeff, intVec pows)
    {
        Powers.push_back(pows);
        Coefficients.push_back(coeff);
    }

    int Dim, DimCoupl;
    std::vector<long> Coefficients;
    std::vector<intVec> Powers;
};

Where IntVec is a custom array of ints that's based on the arrays from the Boost library.

I have an stl Vector of these object, and I'd like to sort them by the amount of elements of their Coefficients vectors. So I define:

bool compInv(const Invariant &one, const Invariant &two)
{
    return (one.Coefficients.size() < two.Coefficients.size());
}

And use std::sort() or std::stable_sort() to sort the Vector. Checking afterwards, the Vector is sorted, but is seems like the content of std::vector<intVec> Powers is changed. Furthermore, std::sort() and std::stable_sort() seem to alter them in a different way. What could be causing this?

Edit: The definition of the IntVec:

typedef blitz::Array<int,1> intVec;

Which I use because they are easier to initialize than regular arrays, which is very important since I have to create a lot of these objects that each contain a lot of these vectors.

Without a SSCCE it's hard to tell what is wrong with your code, but it looks like you're caught by using a class from an outdated library (blitz++), which seemed to have ceased further development/updating/debugging several years ago.

Since blitz::Array<int,1> is a dynamically allocated 1D array of integers, there is no advantage over carefully using std::vector<int> instead, when you get the full support (correct swap) and C++11 features (move semantics). So, the first thing to try is

typedef std::vector<int> intVec;

and see if the symptoms persist. If this involves too many changes to your code, try this first with a SSCCE (which initially must show the same symptoms as your code).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM