如何将两个std :: vector合并成一个std :: vector和std :: pair [英] How to combine two std::vector into a single std::vector with std::pair

查看:3557
本文介绍了如何将两个std :: vector合并成一个std :: vector和std :: pair的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个向量a和b,我想排序a,我想要b重新排序,就像排序的a。

Suppose I have two vectors "a" and "b" and I want to sort "a", and I want "b" to be re-ordered just like the sorted "a".

我可以想到的最合理的方法是将这两个向量组合成一个std :: pair的单一向量,所以我可以应用std :: sort,下面是一个玩具示例

The most logical approach I can think of is combining these two vectors into a single vector of std::pair so I can apply std::sort, below is a toy example

std::vector<int> a(3,1);
std::vector<std::string> b(3,"hi");
std::vector<std::pair<int,std::string>> p(3);

for(int i=0;i<a.size();i++){
  p.push_back(std::make_pair(std::ref(a[i]),std::ref(b[i])));
}

p[0].first = p[0].first+1;

std::cout << p[0].first << " " << a[0] << std::endl;

我希望它打印2 2,但它正在打印2 1.我也尝试更换循环

I am expecting it to print 2 2 but it is printing 2 1. I also attempted replacing the for loop with

for(int i=0;i<a.size();i++){
  p[i].first  = std::ref(a[i]);
  p[i].second = std::ref(b[i]);
}

但它仍然在打印2 1.我可以从p 分类后返回a和b,但是当a和b大时,这将是低效的。我做错了什么?

but it is still printing 2 1. I could copy the values from "p" back to "a" and "b" after sorting but this will be inefficient when "a" and "b" is large. What am I doing wrong?

我的编译器是gcc 4.9.3。

My compiler is gcc 4.9.3.

推荐答案

您想要一个具有如下引用对的向量:

You want a vector of pairs of references there like:

#include <iostream>
#include <string>
#include <vector>
#include <utility>

int main() {
    std::vector<int> a(3,1);
    std::vector<std::string> b(3,"hi");
    std::vector<std::pair<int&, std::string&>> p;

    for(int i=0;i<a.size();i++){
       p.push_back(std::pair<int&, std::string&>(a[i],b[i]));
    }

    p[0].first = p[0].first+1;

    std::cout << p[0].first << " " << a[0] << std::endl;
}

谨防,但并非所有可能的操作都可以完成与参考对。例如。您不能通过无参构造函数创建它的实例。这就是为什么你不能初始化矢量与三个空元素,如在你的例子:

Beware though not every possible operation can be done with pair of references. E.g. you cannot create an instance of it by parameterless constructor. This is why you cannot initialize the vector with three empty elements as in your example:

 std::vector<std::pair<int&, std::string&>> p(3);

这篇关于如何将两个std :: vector合并成一个std :: vector和std :: pair的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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