Is this a valid datastructure Map <string, string, string> in C ++?

I have to store 3 lines for each variable, but I don’t know which one is the best to use for C ++. I can only think of Struct, but I'm not sure if this is the best way to do this.

Something like the string var [100] [3], the first dimension (100) should dynamically add and remove.

I tried all kinds of things with a map, multimap.

Any help is appreciated. thank you

+4
source share
8 answers

If you always have three lines together in a triplet and you want to have several triplets, then define a structure with three lines and put it in std::vector .

 struct Triplet { std::string a,b,c; }; std::vector<Triplet> data; 
+8
source

Map<string, string, string> invalid. However, you can create a new data structure with three rows and save it in a vector.

 #include <iostream> #include <string> #include <vector> using namespace std; class data_structure { public: string first; string second; string third; }; int main() { vector<data_structure> my_vec; data_structure elem1; elem1.first = "one"; elem1.second = "two"; elem1.third = "three"; my_vec.push_back(elem1); data_structure elem2; elem2.first = "four"; elem2.second = "five"; elem2.third = "six"; my_vec.push_back(elem2); for (int i = 0; i < my_vec.size(); i++) { // print stuff } } 
+3
source

you can use class or tuple and save tuple in vector

 std::vector<boost::tuple<std::string, std::string, std::string> > v; boost::tuple<std::string, std::string, std::string> t = boost::make_tuple(s1, s2, s3); v.push_back(t) 
+1
source

If you always want 3 lines, then tuple will require less overhead.

 #include <iostream> #include <string> #include <tuple> typedef std::tuple<std::string, std::string, std::string> MyTuple; int main(int argc, char **argv) { MyTuple t = make_tuple( std::string("string 1"), std::string("string 2"), std::string("string 3") ); std::cout << std::get<0>(t) << std::endl << std::get<1>(t) << std::endl << std::get<2>(t) << std::endl; return 0; } 
+1
source

Another suggestion above: Boost Tuple (if you already have Boost installed).

+1
source

You can use vector to store N elements

 vector<string> three_strings(3); three_strings.push_back("one"); three_strings.push_back("two"); three_strings.push_back("three"); 

Please note that tuple is an alternative, BUT: (1) it is part of the tr1 standard and, therefore, may not be available on your compiler / installation in C ++; (2) It stores heterogeneous data (e.g. 3 random types, not necessarily 3 rows) that may be full

0
source

Map <string , vector <string> > Allows you to map a vector of strings to a string key. If you have the same number of lines associated with each key, then use an array of lines to reduce the memory overhead for the vector.

0
source

What about vector<vector<string> > ?

0
source

Source: https://habr.com/ru/post/1338873/


All Articles