【问题标题】:vector of string vector initialization字符串向量初始化向量
【发布时间】:2013-07-22 21:17:17
【问题描述】:

我想知道如何简化和概括字符串向量向量的初始化:

vector<vector<wstring>> vvValues;

const wchar_t *row1[] = { L"R1C1_variablesize"};
const wchar_t *row2[] = { L"R2C1_vsize" , L"R2C2_varsize", L"R2C3_variabsize"};
const wchar_t *row3[] = { L"R3C1_variablsize", L"R3C2_vasize"};

vvValues.push_back (vector<wstring> (row1, end(vrow1)));
vvValues.push_back (vector<wstring> (row2, end(row2)));
vvValues.push_back (vector<wstring> (row3, end(row3)));

我尝试使用临时数组

const wchar_t **rows[] = {row1, row2, row3);

使用迭代器,我测试成功了

for (auto it = begin(rows); it!= end(rows); ++it)
    vvValues.push_back (vector<std::wstring> (*it, *it + 0));

在 row1、row2、row3 上使用 count()、sizeof() 或 end(),行按预期工作。

-> 但我不知道如何获取每行元素的数量

sizeof(rows[0]) -> 4
sizeof(rows[1]) -> 12
sizeof(rows[2]) -> 8

甚至更好

sizeof(it) -> 4, 12, 8 on each iteration.

非常感谢

你把我带到了这里 工作解决方案

vector<vector<wstring>> vvValues;

// First string -> # of strings excluding index
const wchar_t *row1[] = { L"1", L"R1C1_variablesize"};
const wchar_t *row2[] = { L"3", L"R2C1_vsize" , L"R2C2_varsize", L"R2C3_variabsize"};
const wchar_t *row3[] = { L"2", L"R3C1_variablsize", L"R3C2_vasize"};

const wchar_t **rows[] = {row1, row2, row3);

for (unsigned long it = 0; it < sizeof(rows)/sizeof(wchar_t *); ++it)
    vvValues.push_back (vector<std::wstring> (rows[it] + 1, 
                                       rows[it] + 1 + wcstoul(rows[it][0], NULL, 0)));

【问题讨论】:

  • vector&lt;vector&lt;wstring&gt;&gt; vvValues{{L"..."}, {L"...", L"...", L"..."}, {L"...", L"..."}}; 容易多了。
  • 同意 c++11 “完全” 兼容的编译器,但到目前为止,VC++ 不接受这种合成器。你猜怎么着,我用的是 MS 编译器;)
  • 我相信 VS2013 现在确实支持标准类型,而且几个月后就会真正实现 :)

标签: c++ visual-c++


【解决方案1】:

您是否考虑过以空字符串结束每一行?例如:

const wchar_t **rows[] = {"Hello", "everyone", "", 
                          "start", "of", "row", "2", "", 
                          "now", "three", ""};

您可以在初始化循环中轻松检查空值。

但是,如果您的字符串可以为空,您可以尝试使用一个很少用作标记的奇怪字符串。说"~~12~",或者更好地使用不属于您的语言的Unicode字符。

祝你好运。

【讨论】:

    猜你喜欢
    • 2019-06-17
    • 2011-05-15
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 2018-10-03
    • 2013-05-20
    • 2011-03-04
    • 2018-09-30
    相关资源
    最近更新 更多