通过函数参数传大量数据: std::initializer_list
std::initializer_list 不仅可以用来对自定义类型做初始化, 还可以用来传递同类型的数据集合, 代码如下:
void func(std::initializer_list<int> l)
{
for (auto it = l.begin(); it != l.end(); ++it)
std::cout << *it << std::endl;
}
int main(void)
{
func({}); //一个空集合
func( { 1, 2, 3 }); //传递{ 1, 2, 3 }
return 0;
}
for循环遍历 or for_each遍历:
void test1 ()
{
std::vector<int> arr;
//....
for (auto it = arr.begin(); it != arr.end(); ++it)
{
std::cout<< *it << std::endl;
}
}
void do_count( int n)
{
std::cout<< n << std::endl;
}
void test2()
{
std::vector<int> arr;
//....
std::for_each(arr.begin(), arr.end(), do_count);
}
void test3()
{
std::vector<int> arr = {1,2,3};
//...
for (auto n: arr) { // auto可直接换为int. 若改为auto & 则可以对容器元素修改
std::cout<< n << std::endl;
}
}
std::set 的内部元素是只读的! std::map在用C++11里auto& n: arr类似这种循环遍历时, 是不能修改first的(即key).
std::vector<int>arr={1,2,3,4,5};
auto && __range = (arr);
auto __begin = __range.begin();//__range和arr一样.
迭代器的一种实现: 留意迭代的步长step不一定等于begin-end的约数. step为负数时,operator++实际会减少iterator的值.
template <typename T>
class iterator
{
public:
using value_type = T;
using size_type = size_t;
private:
size_type cursor_;
const value_type step_;
value_type value_;
public:
iterator(size_type cur_start, value_type begin_val, value_type step_val);
value_type operator*() const; //取值
bool operator!=(const iterator& rhs) const;//和另一个迭代器比较
iterator& operator++(void); //prefix ++ operator only
};