打印2d矢量的内容

时间:2012-04-28 22:39:56

标签: c++

这是我正在运行的代码:

std::vector<std::vector<double>> test;
test.push_back(std::vector<double>(30));

 std::vector<std::vector<double> >::iterator it=test.begin(), end=test.end();
    while (it!=end) {
      std::vector<double>::iterator it1=it->first.begin(),end1=it->first.end();
      while (it1!=end1) {
    std::copy(it1.begin(),it1.end(),std::ostream_iterator<double>(std::cout, " "));
    ++it1;
      }
      ++it;
    }

这是我得到的编译错误:

data.cpp:33:45: error: ‘class std::vector<double>’ has no member named ‘first’
data.cpp:33:68: error: ‘class std::vector<double>’ has no member named ‘first’
data.cpp:35:16: error: ‘class std::vector<double>::iterator’ has no member named ‘begin’
data.cpp:35:28: error: ‘class std::vector<double>::iterator’ has no member named ‘end’
data.cpp:35:34: error: ‘ostream_iterator’ is not a member of ‘std’
data.cpp:35:56: error: expected primary-expression before ‘double'

有关如何修复它的任何建议,以便我可以打印测试的内容

2 个答案:

答案 0 :(得分:2)

代码存在两个问题。

首先 std::vectors不包含std::pairs,因此没有firstsecond

while (it!=end) {
  std::vector<double>::iterator it1=it->begin(),end1=it->end();

第二次std::copy的调用需要一个范围,该范围可能与您的一个内部向量相对应。所以你的水平太深了。

您可以迭代外部向量test,然后使用copy为每个元素(即向量)打印。

std::vector<std::vector<double>> test;
test.push_back(std::vector<double>(30));
std::vector<std::vector<double> >::iterator it=test.begin(), end=test.end();
for ( it!= end, ++it) {
  std::copy(it1-begin(),it->end(),std::ostream_iterator<double>(std::cout, " "));
}

答案 1 :(得分:2)

我认为这更符合您的要求。

std::vector<std::vector<double>> test;
// Put some actual data into the test vector of vectors
for(int i = 0; i < 5; ++i)
{
    std::vector<double> random_stuff;
    for(int j = 0; j < 1 + i; ++j)
    {
        random_stuff.push_back(static_cast<double>(rand()) / RAND_MAX);
    }
    test.push_back(random_stuff);
}

std::vector<std::vector<double> >::iterator it=test.begin(), end=test.end();
while (it!=end) 
{
    std::vector<double>::iterator it1=it->begin(),end1=it->end();
    std::copy(it1,end1,std::ostream_iterator<double>(std::cout, " "));
    std::cout << std::endl;
    ++it;
}

您首先不需要,因为您的向量不包含对,并且您不需要基于it1和end1循环,因为它们表示您传递给复制的范围。