std::vector<std::pair<std::string > >
可用於存儲一對字符串的列表。有沒有類似的方式來存儲字符串的三元組列表?我能想到的如何存儲三個字符串集合的列表?
一種方法是使用std::vector
std::vector<std::vector<std::string > > v (4, std::vector<std::string> (3));
但這不會讓我使用handly first
和second
存取。
所以,我寫我自己的類
#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;
}
我有兩個問題
- 可以將我的類代碼以任何方式加以改進?
- 有沒有比上述三種方式更好地存儲三串字符串的方法?
'std :: tuple'是C++ 11中的新增功能,但應該在大多數比幾年前更新的編譯器中可用。 – 2012-03-23 07:43:37