这个 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/