矢量数据不在while循环中添加

时间:2013-12-12 17:07:24

标签: c++ vector while-loop

我试图使用for循环两次将双精度矢量(属于一个名为path的类)的元素添加到一个名为dist的double中。我希望它在第一次迭代中添加类向量内的所有距离,然后在结束时将double dist设置为零并再次添加它们。但是,当我运行它时,它第一次工作正常,因为它打印出正确答案3,但是当它第二次打印出来并且在完成循环之后,双精度结束为0。看起来它没有添加矢量的数据。为什么会这样?谢谢你的帮助

class Path
{
  public:
      vector<double> distance;
      vector<double> safety;
};

int main()
{
     int i = 0;
     int k = 0;
     vector<Path*> paths; 

     Path* paths.at(0) = new Path;
     Path* paths.at(1) = new Path;
     paths.at(0)->distance.push_back(1.0);
     paths.at(0)->distance.push_back(2.0);
     paths.at(1)->distance.push_back(1.0);
     paths.at(1)->distance.push_back(2.0)
     double dist = 0;

     for(k = 0; k < paths.size(); k++)
     {

         for(i = 0; i< paths.at(k)->distance.size(); i++)
         {
              dist += paths.at(i)->distance.at(i);
         }
         cout << dist << endl;
         dist = 0;
    }
    delete paths.at(0); delete paths.at(1);
    return 0;
}

3 个答案:

答案 0 :(得分:0)

for(k = 0; k < route -> distance.size(); k++)
{
    for(i = 0; i< route->distance.size(); i++)
    {
        dist += route->distance.at(i);
    }

    cout << dist << endl;
    dist = 0;
}

这将为您提供k个输出(也就是说,它会在向量k次上进行迭代)。如果您只想迭代向量两次,那么这不是您想要编写循环的方式。相反,你需要2个独立的(不是嵌套的)循环:

for (int i = 0; i < route->distance.size(); ++i)
{
    dist += route->distance[i];
}
cout << dist << endl;

dist = 0;
for (int k = 0; k < route->distance.size(); ++k)
{
    dist += route->distance[k];
}
cout << dist << endl;

或者你可以使用一个能为你做到这一点的功能:

dist = std::accumulate(route->distance.begin(), route->distance.end(), 0);

修改

通过更新,您现在无效操作:

vector<Path*> paths; 
Path* paths.at(0) = new Path; // at(0) does not exist!  exception will be thrown
Path* paths.at(1) = new Path; // same here

答案 1 :(得分:0)

这一行有一个错误:

dist += paths.at(i)->distance.at(i);

应该是:

dist += paths.at(k)->distance.at(i);

答案 2 :(得分:0)

这是C ++,使用它的力量:

#include <numeric>
#include <vector>
#include <iostream>

struct Path
{
    std::vector<double> distance;
    std::vector<double> safety;
};

int main()
{
    std::vector<Path> paths{
        {
            { 1.0, 2.0 }, {}
        },
        {
            { 3.0 }, {}
        }
    };

    // loop version
    double sum = 0.0;
    for ( auto const& path : paths ) {
        for ( double d : path.distance ) {
            sum += d;
        }
    }
    std::cout << sum << std::endl;
    // ...

算法版本

    std::cout <<
        std::accumulate(
        paths.begin(),
        paths.end(),
        0,
        [](double res, Path const& path) {
            return res + std::accumulate(
                          path.distance.begin(),
                          path.distance.end(),
                          0);
        })
     <<std::endl;
}

-> Ideone

  • 使用RAII
  • 如果您坚持循环,则使用algorithms基于范围的循环
  • 不要忘记软件设计