【问题标题】:How to iterate through a vector of tuples using iterator or any other way in c++如何使用迭代器或c ++中的任何其他方式遍历元组向量
【发布时间】:2020-10-14 22:07:18
【问题描述】:
std::vector<std::tuple<PCWSTR, PCWSTR,PCWSTR> > tempVector;
tempVector.push_back({ L"temp", L"temp1", L"temp2" });
tempVector.push_back({ L"data", L"data1", L"data2" });

const ULONG fieldCount = tempVector.size();

PCWSTR fieldNames = new PCWSTR[fieldCount];
PCWSTR fieldValues = new PCWSTR[fieldCount];
PCWSTR fieldSize = new PCWSTR[fieldCount];   
int index=0;
for (std::vector<std::tuple<PCWSTR, PCWSTR, PCWSTR>>::iterator it = tempVector.begin(); it != tempVector.end(); ++it) {
        fieldNames[index] = it->_Myfirst;// I know this is incorrect code, how do I fetch the first value here..
        fieldValues[index] = it->second;  
        fieldSize[index] = it->third;           
        index++;
    }

有没有其他方法可以迭代这些元组值并将其填充到数组中...

【问题讨论】:

  • std::vector&lt;std::tuple&lt;PCWSTR, PCWSTR, PCWSTR&gt;&gt;::iterator 和“最佳案例使用auto”的每周奖授予...
  • A range-based for loop 比手动使用迭代器要好
  • 如何使用自动,我确实看到了几个例子,但不太确定......
  • @RemyLebeau 你能给我一个链接吗.. 不知道如何使用它..
  • @ccoding 只需将那个大的长类型名称换成auto 就可以了。

标签: c++ vector iterator tuples


【解决方案1】:

std::tuple 没有为其各个元素命名的字段。但是你可以使用std::get()通过索引单独访问它们,例如:

int index = 0;
for (std::vector<std::tuple<PCWSTR, PCWSTR, PCWSTR>>::iterator it = tempVector.begin(); it != tempVector.end(); ++it) {
    fieldNames[index] = std::get<0>(*it);
    fieldValues[index] = std::get<1>(*it);
    fieldSize[index] = std::get<2>(*it);
    ++index;
}

或者,您可以改用std::tie(),例如:

int index = 0;
for (std::vector<std::tuple<PCWSTR, PCWSTR, PCWSTR>>::iterator it = tempVector.begin(); it != tempVector.end(); ++it) {
    std::tie(fieldNames[index], fieldValues[index], fieldSize[index]) = *it;
    ++index;
}

现在,话虽如此,您可以改用auto 来简化迭代器声明,例如:

for (auto it = tempVector.begin(); it != tempVector.end(); ++it) {

不过,您确实应该使用range-based for loop 而不是手动迭代器循环,例如:

size_t index = 0;
for (auto &t : tempVector) {
    // Either:
    fieldNames[index] = std::get<0>(t);
    fieldValues[index] = std::get<1>(t);
    fieldSize[index] = std::get<2>(t);

    // Or:
    std::tie(fieldNames[index], fieldValues[index], fieldSize[index]) = t;

    ++index;
}

您确实应该手动使用std::vector 而不是new[],例如:

std::vector<PCWSTR> fieldNames(fieldCount);
std::vector<PCWSTR> fieldValues(fieldCount);
std::vector<PCWSTR> fieldSize(fieldCount);

【讨论】:

    猜你喜欢
    • 2020-07-26
    • 1970-01-01
    • 2015-08-12
    • 2016-09-03
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多