【问题标题】:Suitable data type for looping through c++ vectors用于循环 c++ 向量的合适数据类型
【发布时间】:2015-11-13 21:16:15
【问题描述】:

我有这样的代码:

std::vector<std::vector<double> > solutions;
std::vector<double> test_vals(5);
for(int i = 0; i < 10; i++)
{
    test_vals = getDoubleVector();
    if (/*some condition*/)
    {
        solutions.push_back(test_vals);
    }
}

现在,当我尝试使用这种技术遍历向量时,它会在运行时崩溃:

for(std::size_t i = 0; i < solutions.size(); i++)
{
    for(int j = 0; j < 5; j++)    
    {
        std::cout << solutions[i][j] << std::endl;
    }
}

使用此行作为内部循环的 for 条件也会导致崩溃:

for(std::size_t j = 0; j < solutions[i].size(); j++)

只有“正确”的方法才有效:

for(std::vector<double>::size_type j = 0; j < solutions[i].size(); j++)

问题是,我对j 的哪种数据类型适用于何处感到有些困惑。我使用简单的int 变量来遍历字符串向量,并且效果很好。它也适用于我随时间使用的一些自定义数据类型,那么为什么不在这里呢?另外,std::size_t 适合什么情况?在示例中,我认为使用更安全的方法是有意义的,但如果我需要这样做:

for(std::vector<double>::size_type j = 0; j < solutions[i].size(); j++)
{
    std::vector</*some other data type*/> vector2(5);
    vector2[j].double_val = solutions[i][j];
}

现在我需要为vector2 携带一个单独的size_type 还是有什么方法我也可以在这里使用j

【问题讨论】:

  • j 的类型不可能是您崩溃的实际原因。我敢打赌,您的程序中还潜伏着其他错误。
  • 查看崩溃的调用栈/看看solution[i]的实际大小向量元素是多少

标签: c++ vector iterator


【解决方案1】:

忘记索引,你甚至没有使用它。

for (const auto& solution : solutions)
{
    for (const auto& item : solution)
        std::cout << item << std::endl;
}

【讨论】:

  • 我知道索引可以完全避免(我有时自己使用迭代器)。只是想了解底层机制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
相关资源
最近更新 更多