C ++使用自定义键和值或类似的东西制作数组

时间:2012-03-23 11:13:54

标签: c++ arrays

我有一个函数,我设置自定义键和值,我想将它们返回到接收器,以便他们可以看到,我希望能够看到键和值,以便我可以用它做一些事情,就像在这个例子中我打印它们。

我放下的例子非常清楚我想要的是什么。

//#functions.cpp

something returnKeyAndValue(){
     something valor;
     valor.login = "hey";
     valor.senha = "you";
     return valor;
}

something returnKeyAndValue2(){
     something valor;
     valor.value2 = "hello";
     valor.value1 = "string";
     return valor;
}

//... And a lot of other returnKeyAndValue functions

something PrintKeyAndValuesOfBoth(something KeyAndValue){

    for(int i = 0; i < KeyAndValue.size(); i++){
       string key = KeyAndValue[i].key;
       string value = KeyAndValue[i].value;

       cout << "Key: " << key << ", Val: " << value << endl;
    }

}

//#test.cpp

#import "functions.cpp"

int main () {

    something return = returnKeyAndValue();
    something return2 = returnKeyAndValue2();

     PrintKeyAndValuesOfBoth(return);
     PrintKeyAndValuesOfBoth(return2);

}

这样的“东西”类型可以做什么类似的事情,我将如何获得它的关键和价值。

我希望我足够清楚。 提前谢谢。

@Edit - 解决方案

使用Dvir Volk提供的地图的想法,基于他的建议,我做了这个例子来展示如何使用它。

#include <stdio.h>
#include <iostream>
#include <string>
#include <map>
#include <conio.h>

int main () {

    std::map< std::string, std::string > MyMap;
    std::map< std::string, std::string >::iterator MyIterMap; 

       MyMap["Teste1"] = "map1";
       MyMap["Teste2"] = "map2";
       MyMap["Teste3"] = "map3";

   MyIterMap = MyMap.begin(); 

   while(MyIterMap != MyMap.end() ) {
       std::string key = (*MyIterMap).first; 

       std::cout << "Key: " << key << ", Value: " << MyMap[key] <<std::endl;
       MyIterMap++;
   }
   _getch();
   return 0;

}

希望我帮助过。

1 个答案:

答案 0 :(得分:4)

您需要std :: map或std :: unordered_map。 您需要实现散列或比较功能(对于map)以使用自定义键而不是基本类型。

你当然可以创建一对矢量,但它不会是一个关键和值。

见这里:http://en.cppreference.com/w/cpp/container/map