你所说的“可以传址调用但又能直接输出”是指的什么?
但现在有个特殊要求,想将结构体作为索引,应该怎么办呢,下面写了一段测试代码来展示怎么使用。头文件中定义一个结构:typedef struct TESTSTRUCT{int iint jbool operator<(const TESTSTRUCT &rhs) const{return ( this->i<rhs.i)}}TESTSTRUCT具体使用:map<TESTSTRUCT,int>mapTestTESTSTRUCT mapindexmapindex.i = 1mapindex.j = 2typedef pair<TESTSTRUCT,int>STPARmapTest.insert(STPAR(mapindex,6))mapindex.i = 4mapTest.insert(STPAR(mapindex,7))}这里的关键其实就是定义结构时需要重载<,因为map在插入数据时是自动排序的,在没有指定排序方法时,使用<来进行排序,因为定义的TESTSTRUCT比大小的功能,因此重载<就可以使之比大小,这里用的是其中的元素i。在具体的使用中,索引的值也可以是结构。map 是以 pair形式插入的。
map中的元素的类型value_type
typedef pair<const Key, Type>value_type
value_type 被声明为 pair <const key_type, mapped_type>但并不是简单的 pair <key_type, mapped_type>因为用一个非常量的迭代器或引用不能改变关联容器的Key。
#include <map>
#include <iostream>
int main( )
{
using namespace std
typedef pair <const int, int> cInt2Int
map <int, int> m1
map <int, int> :: key_type key1
map <int, int> :: mapped_type mapped1
map <int, int> :: value_type value1
map <int, int> :: iterator pIter
// value_type can be used to pass the correct type
// explicitly to avoid implicit type conversion
m1.insert ( map <int, int> :: value_type ( 1, 10 ) )
// Compare other ways to insert objects into a map
m1.insert ( cInt2Int ( 2, 20 ) )
m1[ 3 ] = 30
// Initializing key1 and mapped1
key1 = ( m1.begin( ) -> first )
mapped1 = ( m1.begin( ) -> second )
cout << "The key of first element in the map is "
<< key1 << "." << endl
cout << "The data value of first element in the map is "
<< mapped1 << "." << endl
// The following line would cause an error because
// the value_type is not assignable
// value1 = cInt2Int ( 4, 40 )
cout << "The keys of the mapped elements are:"
for ( pIter = m1.begin( ) pIter != m1.end( ) pIter++ )
cout << " " << pIter -> first
cout << "." << endl
cout << "The values of the mapped elements are:"
for ( pIter = m1.begin( ) pIter != m1.end( ) pIter++ )
cout << " " << pIter -> second
cout << "." << endl
}
Output
The key of first element in the map is 1.
The data value of first element in the map is 10.
The keys of the mapped elements are: 1 2 3.
The values of the mapped elements are: 10 20 30.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)