向量作为键如何在C ++中内部工作?

问题描述 投票:12回答:2

此SO回答说,向量STL Map with a Vector for the Key可用作键。因此,当我们使用向量作为键时。由于键需要唯一,因此该键实际如何工作,因此当我们插入另一个具有相同元素的向量时,map将逐个元素检查重复的元素,或者向量的名称确实指定了什么吗?就像数组的名称代表基地址一样。因此,可以将数组用作键,因为在这种情况下基地址可以用作键,但是在矢量情况下,键是什么。它如何在内部工作。

因为当我打印矢量的名称时,确实出现错误

vector<int> v;
cout<<v; //error
c++ arrays dictionary vector stl
2个回答
9
投票

对于类模板std :: vector,有一个重载的运算符

template <class T, 
class Allocator>
bool operator< (const vector<T, Allocator>& x, const vector<T, Allocator>& y);

基于标准算法std::lexicographical_compare

这里是演示程序。

#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <algorithm>

int main() 
{
    std::vector<int> v1 = { 1, 2 };
    std::vector<int> v2 = { 1, 2, 3 };
    std::vector<int> v3 = { 2 };

    std::cout << std::boolalpha << ( v1 < v2 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v1 ), std::end( v1 ),
                                               std::begin( v2 ), std::end( v2 ) )
             << '\n';                                              

    std::cout << std::boolalpha << ( v1 < v3 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v1 ), std::end( v1 ),
                                               std::begin( v3 ), std::end( v3 ) )
             << '\n';                                              

    std::cout << std::boolalpha << ( v2 < v3 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v2 ), std::end( v2 ),
                                               std::begin( v3 ), std::end( v3 ) )
             << '\n';                                              

    return 0;
}

其输出为

true
true
true
true
true
true

因此该类可用作地图中的键。

默认情况下,类模板映射使用函数对象std ::: less,而依次使用运算符<

template <class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T>>>
class map 
{
    //...
};

但是,对于类模板std :: vector没有重载运算符<


8
投票

对象的名称和该对象的内容始终是无关的东西。

operator ==的[std::vector首先将比较向量的长度,然后再使用operator ==比较每个元素。

[operator <从字典上比较向量中的元素,即,它为向量x[i] < y[i]x中的第一个不等元素返回y

这些是std::map对用作Key的类型的要求。由于std::vector满足这两个要求,因此可以用作Key。请注意,由vector管理的类型还必须使这些运算符重载才能正常工作(因为std::vector依靠那些运算符来实现它自己的运算符)。

© www.soinside.com 2019 - 2024. All rights reserved.