如何使用迭代器来迭代2D向量? [英] How to use iterator to iterate a 2D vector?

查看:88
本文介绍了如何使用迭代器来迭代2D向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

all



我使用C ++ STL中的向量来存储我的数据。我传递和返回它们从函数。然而,随着数据大小的增长,程序越来越慢。因此,我将代码更新为迭代器版本。



我想要的是使用迭代器传递,返回和迭代STL向量<强>。



我现在确定与1维向量的操作,就像操作数组。但是,当涉及到二维向量时,我有点困惑。



任何人都可以显示一个简单的代码示例,如何迭代2D向量使用STL迭代器



非常感谢。




$ b

解决方案

很好它已经在stackoverflow上了。



但是如果你不想在这里搜索它是:

  std :: vector< std: :vector  > vec {{1,2,3},{4,5,6}}; 

//最简单的方法: - (C ++ 11)

for(auto row:vec)
{
for )
std :: cout<< col<< ;
std :: cout<< std :: endl;
}

//使用迭代器
std :: vector< std :: vector< int> > :: iterator r;
std :: vector< int> :: iterator c;
for(r = vec.begin(); r!= vec.end(); r ++){
for(c = r-> begin(); c!= r-> end (); c ++){
std :: cout<< * c< ;
}
std :: cout<< std :: endl;
}

可以获得距离

  std :: vector< int> :: iterator s = v2.begin(); //可以是任何开始
std :: vector< int> :: iterator e = v2.end(); //可以是任何结束

std :: cout<<Distance:<<< std :: distance(s,e)<< std :: endl;


all

I am using vector in C++ STL to store my data. I pass and return them into and from functions. However, as the data size grows, the program is slower and slower. Thus I am updating the codes to an "iterator version".

What I want to archieve is that use iterators to pass, return and iterate STL vectors.

I am now ok with the operations with 1-dimensional vector, just like manipulating the arrays. However, when it comes to 2-dimensional vector, I am a bit confused.

Can anyone show me a simple code example that how to iterate a 2D vector using STL iterator?

Many thanks in advance.

Regards

Long

解决方案

Well its already somewhere on stackoverflow

But if you don't want to search here it is :

std::vector<std::vector<int> >  vec{ {1,2,3},{4,5,6}};

//Simplest Way:- (C++11)

for(auto row:vec)
{
  for(auto col:row)
   std::cout<<col<< " ";
  std::cout<<std::endl;
}

//OR Using iterator
std::vector<std::vector<int> >::iterator r;
std::vector<int>::iterator c;
for (r = vec.begin(); r != vec.end(); r++) {
    for (c = r->begin(); c != r->end(); c++) {
        std::cout<<*c<< " ";
    }
    std::cout<<std::endl;
}

Can get distance only between two iterators of same container

std::vector<int>::iterator s = v2.begin(); //Can be any start
std::vector<int>::iterator e = v2.end(); // Can be any end

std::cout<<"Distance :"<<std::distance(s,e)<<std::endl;

这篇关于如何使用迭代器来迭代2D向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆