如何确保在C ++中以相同顺序对两个不同的向量进行混洗? [英] How to ensure two different vectors are shuffled in the same order in C++?

查看:103
本文介绍了如何确保在C ++中以相同顺序对两个不同的向量进行混洗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个向量:

vector1 = [1 2 3 4 5 6 7 8 9]

vector1 = [1 2 3 4 5 6 7 8 9]

vector2 = [1 2 3 4 5 6 7 8 9]

vector2 = [1 2 3 4 5 6 7 8 9]

我想确保,当我同时使用 random_shuffle 进行混洗时,应按照相同的顺序进行混洗.例如:

I want to ensure, that when I shuffle both using random_shuffle they should be shuffled in the same corresponding order. For example:

改组后的输出应为:

vector1 = [1 9 3 4 2 7 8 5 6]

vector1 = [1 9 3 4 2 7 8 5 6]

vector2 = [1 9 3 4 2 7 8 5 6]

vector2 = [1 9 3 4 2 7 8 5 6]

但是我得到的输出如下:

But I am getting output like:

vector1 = [5 1 7 4 2 3 9 8 6]

vector1 = [5 1 7 4 2 3 9 8 6]

vector2 = [3 4 1 9 8 2 5 7 6]

vector2 = [3 4 1 9 8 2 5 7 6]

这里是我的代码:

int main () 
{
  std::srand ( unsigned ( std::time(0) ) );
  std::vector<int> vector1, vector2;

  // set some values:
  for (int i=1; i<10; ++i)
  {
    vector1.push_back(i);
    vector2.push_back(i);
  }

  // using built-in random generator:
  std::random_shuffle ( vector1.begin(), vector1.end() );
  std::random_shuffle ( vector2.begin(), vector2.end() );

  // print out content:
  std::cout << "vector1 contains:";
  for ( std::vector<int>::iterator it1 = vector1.begin(); it1 != vector1.end(); ++it1 )
    std::cout << ' ' << *it1;

  std::cout << '\n';
  std::cout << '\n';

  std::cout << "vector2 contains:";
  for ( std::vector<int>::iterator it2 = vector2.begin(); it2 != vector2.end(); ++it2 )
    std::cout << ' ' << *it2;

  std::cout << '\n';
  std::cout << '\n';

  return 0;
}

EDIT (这是我尝试实现的一个示例案例).实际上,我有一个图像矢量和一个对应标签矢量.我需要以同样的方式将它们洗牌.任何人都可以帮忙...... 非常感谢!

EDIT This is an example case that I tried to implement. In practise, I have one vector of images and one vector of corresponding labels. I need them to be shuffled in the same manner. Could anybody please help...... thanks a lot!!

推荐答案

与其将向量本身改组,反而将索引向量改组为其他向量.由于您将对两者使用相同的索引,因此可以确保它们的顺序相同.

Instead of shuffling the vectors themselves, shuffle a vector of indexes into the other vectors. Since you'll be using the same indexes for both, they're guaranteed to be in the same order.

std::vector<int> indexes;
indexes.reserve(vector1.size());
for (int i = 0; i < vector1.size(); ++i)
    indexes.push_back(i);
std::random_shuffle(indexes.begin(), indexes.end());

std::cout << "vector1 contains:";
for ( std::vector<int>::iterator it1 = indexes.begin(); it1 != indexes.end(); ++it1 )
    std::cout << ' ' << vector1[*it1];

这篇关于如何确保在C ++中以相同顺序对两个不同的向量进行混洗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆