[英]printing contents of 2d vector
這是我正在運行的代碼:
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'
關於如何修復它的任何建議,以便我可以打印測試的內容
代碼有兩個問題。
第一個 std::vectors
不包含std::pairs
,因此沒有first
或second
:
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, " "));
}
我認為這更是您想要的。
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進行循環,因為它們表示傳遞給您的復制范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.