如何通过不同的std :: vector的值对std :: vector进行排序?

Joh*_*ter 53 c++ sorting boost stl vector

我有几个std::vector,全长相同.我想对这些向量中的一个进行排序,并将相同的变换应用于所有其他向量.这样做有一个简洁的方法吗?(最好使用STL或Boost)?一些向量包含ints,其中一些包含std::strings.

伪代码:

std::vector<int> Index = { 3, 1, 2 };
std::vector<std::string> Values = { "Third", "First", "Second" };

Transformation = sort(Index);
Index is now { 1, 2, 3};

... magic happens as Transformation is applied to Values ...
Values are now { "First", "Second", "Third" };
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 31

friol的方法与你的方法很好.首先,构建一个由数字1 ... n组成的向量,以及来自向量的元素,指示排序顺序:

typedef vector<int>::const_iterator myiter;

vector<pair<size_t, myiter> > order(Index.size());

size_t n = 0;
for (myiter it = Index.begin(); it != Index.end(); ++it, ++n)
    order[n] = make_pair(n, it);
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用自定义排序器对此数组进行排序:

struct ordering {
    bool operator ()(pair<size_t, myiter> const& a, pair<size_t, myiter> const& b) {
        return *(a.second) < *(b.second);
    }
};

sort(order.begin(), order.end(), ordering());
Run Code Online (Sandbox Code Playgroud)

现在你已经捕捉到内部重新排列的顺序order(更确切地说,在项目的第一个组件中).您现在可以使用此排序来对其他向量进行排序.可能有一个非常聪明的就地变体在同一时间运行,但在其他人提出它之前,这里有一个不适合的变体.它order用作每个元素的新索引的查找表.

template <typename T>
vector<T> sort_from_ref(
    vector<T> const& in,
    vector<pair<size_t, myiter> > const& reference
) {
    vector<T> ret(in.size());

    size_t const size = in.size();
    for (size_t i = 0; i < size; ++i)
        ret[i] = in[reference[i].first];

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,这就是我想到的那种解决方案,我只是想知道是否有一些很好的方法将相同的转换应用于几个向量,但我猜不是. (2认同)

lal*_*itm 9

typedef std::vector<int> int_vec_t;
typedef std::vector<std::string> str_vec_t;
typedef std::vector<size_t> index_vec_t;

class SequenceGen {
  public:
    SequenceGen (int start = 0) : current(start) { }
    int operator() () { return current++; }
  private:
    int current;
};

class Comp{
    int_vec_t& _v;
  public:
    Comp(int_vec_t& v) : _v(v) {}
    bool operator()(size_t i, size_t j){
         return _v[i] < _v[j];
   }
};

index_vec_t indices(3);
std::generate(indices.begin(), indices.end(), SequenceGen(0));
//indices are {0, 1, 2}

int_vec_t Index = { 3, 1, 2 };
str_vec_t Values = { "Third", "First", "Second" };

std::sort(indices.begin(), indices.end(), Comp(Index));
//now indices are {1,2,0}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用"indices"向量来索引"Values"向量.


Dav*_*ier 8

将您的值放在Boost Multi-Index容器中,然后迭代以按您想要的顺序读取值.如果您愿意,甚至可以将它们复制到另一个向量中.