Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a list of sets of three strings?

Tags:

c++

std::vector<std::pair<std::string > >

can be used to store a list of a pair of strings. Is there a similar way to store a list of triplets of strings?

One way I can think of is to use std::vector

std::vector<std::vector<std::string > > v (4, std::vector<std::string> (3));

but this will not allow me to use the handly first and second accessors.

So, I wrote my own class

#include <iostream>
#include <vector>
using namespace std;

template <class T>
class triad {
private:
    T* one;
    T* two;
    T* three;
public:
    triad() {  one = two = three =0;  }
    triad(triad& t) {
        one = new T(t.get1());
        two = new T(t.get2());
        three = new T(t.get3());
    }
    ~triad() {
        delete one;
        delete two;
        delete three;
        one = 0;
        two = 0;
        three = 0;
    }
    T& get1() { return *one; }
    T& get2() { return *two; }
    T& get3() { return *three; }
};

int main() {
    std::vector< triad<std::string> > v;
}

I have two questions

  1. Can my class code be improved in any way?
  2. Is there any better way to do store triplets of strings than the three ways described above?
like image 216
Lazer Avatar asked Dec 02 '22 23:12

Lazer


2 Answers

std::tuple is a generalization of std::pair that lets you store a collection of some size that you specify. So, you can say:

typedef std::tuple<std::string, std::string, std::string> Triad;

to get a type Triad that stores three strings.

like image 195
Caleb Avatar answered Dec 19 '22 21:12

Caleb


You can use tuples from boost: http://www.boost.org/doc/libs/1_49_0/libs/tuple/doc/tuple_users_guide.html

(In C++11 tuples are part of standard library: http://en.wikipedia.org/wiki/C%2B%2B11#Tuple_types)

like image 26
psur Avatar answered Dec 19 '22 22:12

psur