I have a function that I set custom key and value to it and I would like to return them to a receiver so they can see, I want to be able to see the key and the value so I can do something with it, like in this example I print them.
The example I put down there it’s pretty clear what I want.
//#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);
}
What could be this "something" type to do that something like it, how would I get the key and value of it.
I hope I was clear enough.
Thanks in advance.
@Edit – Solution
Idea of using map provided by Dvir Volk, based on his suggestion I made this example to show how to use it.
#include <iostream>
#include <string>
#include <map>
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++;
}
std::cin.get();
return 0;
}
Hope I helped.
You need std::map or std::unordered_map.
You’ll need to implement hashing or comparison function (for map) to use a custom key and not a primitive type.
You can of course create a vector of pairs, but then it will not be a key and value.
see here: http://en.cppreference.com/w/cpp/container/map