简体   繁体   English

C ++:迭代向量

[英]C++ : iterating the vector

I'm very new to C++ and I'm trying to learn the vector in C++.. 我是C ++的新手,正在尝试学习C ++中的向量。

I wrote the small program as below. 我写了下面的小程序。 I like to foreach(var sal in salaries) like C# but it doesn't allow me to do that so I googled it and found that I have to use iterator.. Im able to compile and run this program but I dont get the expected output.. I'm getting "0 0 0 0 0 0 1 2 3 4 5 6 7 8 9" instead of "0 1 2 3 4 5 6 7 8 9".. 我喜欢像C#一样foreach(薪水不等),但是它不允许我这样做,所以我用Google搜索了它,发现我必须使用迭代器。输出。我得到的是“ 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9”,而不是“ 0 1 2 3 4 5 6 7 8 9”。

Could anyone please explain me why? 谁能解释一下为什么? Thanks. 谢谢。

#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;

void show(int i)
{
  cout << i << " ";
}

int main(){

    vector<int> salaries(5);

    for(int i=0; i < 10; i++){
        salaries.push_back(i);
    }

    for_each(salaries.begin(), salaries.end(), show);   
}

You created a vector with 5 elements, then you push 10 more onto the end. 您创建了一个包含5个元素的向量,然后将10个元素推到最后。 That gives you a total of 15 elements, and the results you're seeing. 这样一来,您总共可以获得15个元素,并且看到的是结果。 Try changing your definition of the vector (in particular the constructor call), and you'll be set. 尝试更改向量的定义(尤其是构造函数调用),您将被设置。 How about: 怎么样:

vector<int> salaries;

This code creates a vector with a size of 5, and with each of those 5 elements initialized to their default value (0): 这段代码创建一个大小为5的向量,并将这5个元素中的每个元素初始化为默认值(0):

vector<int> salaries(5);

push_back inserts a new element, so here, you insert 10 new elements, ending up with a vector with 15 elements: push_back插入一个元素,因此,在此处插入10个新元素,最后以包含15个元素的向量结尾:

for(int i=0; i < 10; i++){
    salaries.push_back(i);
}

You can create your vector like this instead: 您可以这样创建向量:

vector<int> salaries;

and you'll get a vector with size 0. 您将得到一个大小为0的向量。

Alternatively, you could initialize it with size 10, and then overwrite each element, instead of inserting new ones: 另外,您可以使用大小10对其进行初始化,然后覆盖每个元素,而不是插入新元素:

vector<int> salaries(10);

for(int i=0; i < 10; i++){
    salaries[i] = i;
}

In some cases, it may be more efficient to write something like this: 在某些情况下,编写这样的内容可能会更有效:

vector<int> salaries; // create a vector with size 0
// allocate space for 10 entries, but while keeping a size of 0
salaries.reserve(10); 

for(int i=0; i < 10; i++){
    // because we reserved space earlier, these new insertions happen without
    // having to copy the vector contents to a larger array.
    salaries.push_back(i); 
}

When you declare salaries(5), it's adding 5 entries into the vector with values of 0. Then your loop adds 0..9. 当声明salaries(5)时,它将向向量中添加5个条目,其值为0。然后,循环将添加0..9。 Therefore you have 15 elements in your vector instead of just 10. Try declaring the vector without the 5. 因此,向量中有15个元素,而不是10个。尝试声明不带5的向量。

vector<int> salaries;

vector<int> salaries(5); means, that you are creating the vector which contains 5 int objects from the start, and each int object is initialized with default constructor, and in the case of int contructor sets zero value. 就是说,您正在创建一个从头开始包含5个int对象的向量,并且每个int对象都使用默认构造函数初始化,并且在int情况下,contructor设置了零值。 That's why you have 5 zero integers at the beginning of the vector container. 这就是为什么在向量容器的开头有5个零整数的原因。

@Michael: Which book is that? @Michael:那是哪本书? I'd say it's wrong. 我会说这是错误的。 Using resize() is a good practice if you know in advance how big you need the vector to be, but don't set the size at creation unless you need the vector to contain default-initialized values. 如果事先知道需要向量的大小,那么使用resize()是一个好习惯,但是除非在创建向量时需要包含默认初始化的值,否则不要在创建时设置大小。

You can also reserve some capacity in the array in advance which is subtely different than re-size. 您还可以提前在阵列中保留一些与重新调整大小完全不同的容量。 Reserving simply reserves "at least" that much capacity for the vector (but does not change the size of the vector), while resize adds\\removes elements to\\from the vector to make it the requested size. 保留只是简单地“至少”为向量保留了这么多的容量(但不会更改向量的大小),而resize会向向量中添加\\ /删除向量中的元素,以使其达到请求的大小。

vector<int> salaries(5);

This creates a vector of 5 zeros for its elements. 这将为其元素创建一个由5个零组成的向量。 [0, 0, 0, 0, 0] [0,0,0,0,0]

for(int i=0; i < 10; i++){
    salaries.push_back(i);
}

This adds 10 more elements at the end ranging from 0 to 9 [0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 这会在0到9的末尾添加另外10个元素[0、0、0、0、0、0、1、2、3、4、5、6、7、8、9]

Finally, I don't recommend using foreach so much. 最后,我不建议过多使用foreach。 Functional programming has the downside of decentralizing code. 函数式编程的缺点是分散代码。 It is extremely useful in some cases, but for these cases, and especially considering how you're starting out, I'd recommend: 在某些情况下,它非常有用,但是对于这些情况,尤其是考虑到您的入门方式,我建议:

for (vector<int>::const_iterator it = salaries.begin(), end = salaries.end(); it != end; ++it){
    salaries.push_back(i);
}

Using this technique, you'll be able to iterate through any collection in the standard library without having to write separate functions or function objects for the loop body. 使用这种技术,您将能够遍历标准库中的任何集合,而不必为循环体编写单独的函数或函数对象。

With C++0x you'll get a lot of goodies to make this easier: 使用C ++ 0x,您将获得很多好处,可以使此操作更容易:

for (int salary: salaries)
    cout << salary << endl;

There's also BOOST_FOR_EACH already which is almost as easy if you can use boost. 已经有了BOOST_FOR_EACH,如果您可以使用boost,它几乎一样容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM