c++ - 作为键的 vector 如何在 C++ 内部工作?

标签 c++ arrays dictionary vector stl

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

因为当我打印 vector 的名称时,我确实收到错误

vector<int> v;
cout<<v; //error

最佳答案

类模板 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

因此该类可以用作 map 中的键。

默认情况下,类模板映射使用函数对象 std::less ,后者又使用运算符 <
template <class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T>>>
class map 
{
    //...
};

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

关于c++ - 作为键的 vector 如何在 C++ 内部工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60260485/

相关文章:

dictionary - 文本文件中有任何公开可用的单词词典吗?

c++ - 注册后如何设置窗口的背景颜色?

c++ - C语言多线程串口编程

c++ - 如何将整数数组从 Tcl 传递到 C++?

javascript - 获取数组中特定参数为空的第一项

python - 如何从Python3中的输入字符串创建字典

c++ - 解压缩附加的压缩字符串

c++ - 使用 C++ 在 Windows 上发送/接收以太网帧

ios - 遍历数组时在 iOS 中发布更新标签

c# - spring.net注入(inject)字典顺序问题?