gpt4 book ai didi

c++ - 如何存储三个字符串集的列表?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:28 25 4
gpt4 key购买 nike

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

可用于存储一对字符串的列表。有没有类似的方法来存储字符串的三元组列表?

我能想到的一种方法是使用 std::vector

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

但这不允许我使用方便的firstsecond 访问器。

所以,我写了自己的类

#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;
}

我有两个问题

  1. 我的类(class)代码能否以任何方式改进?
  2. 有没有比上述三种方法更好的存储字符串三元组的方法?

最佳答案

std::tuplestd::pair 的泛化,可让您存储指定大小的集合。所以,你可以说:

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

获取存储三个字符串的 Triad 类型。

关于c++ - 如何存储三个字符串集的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9835552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com