我不熟悉c++语言。我已经开始使用向量,并注意到在我看到的所有通过索引遍历向量的代码中,for循环的第一个参数总是基于向量的值。在Java中,我可以对数组列表做这样的事情:

for(int i=0; i < vector.size(); i++){
   vector[i].doSomething();
}

我在c++中看不到这个的原因是什么呢?这是不好的做法吗?


当前回答

在vector上迭代并打印其值的正确方法如下:

#include<vector>

// declare the vector of type int
vector<int> v;

// insert elements in the vector
for (unsigned int i = 0; i < 5; ++i){
    v.push_back(i);
}

// print those elements
for (auto it = v.begin(); it != v.end(); ++it){
    std::cout << *it << std::endl;
}

但至少在目前的情况下,使用基于范围的for循环会更好: 对于(auto x: v) std::cout << x << "\n"; (你也可以在auto后面加上&,使x成为对元素的引用,而不是它们的副本。它与上面的基于迭代器的方法非常相似,但更易于读写。)

其他回答

有什么原因让我在c++中看不到这个吗?这是不好的做法吗?

不。这不是一个不好的实践,但是下面的方法使您的代码具有一定的灵活性。

通常,在c++ 11之前,迭代容器元素的代码使用迭代器,类似于:

std::vector<int>::iterator it = vector.begin();

这是因为它使代码更加灵活。

所有标准库容器都支持并提供迭代器。如果在开发的后期需要切换到另一个容器,则不需要更改此代码。

注意:编写适用于所有可能的标准库容器的代码并不像看起来那么容易。

这是一个更简单的方法来迭代和打印值在向量。

for(int x: A) // for integer x in vector A
    cout<< x <<" "; 

令我惊讶的是,没有人提到遍历具有整数索引的数组会很容易通过下标具有错误索引的数组来编写错误代码。例如,如果使用i和j作为下标嵌套循环,则可能错误地将数组下标为j而不是i,从而在程序中引入错误。

相比之下,这里列出的其他形式,即基于范围的for循环和迭代器,更不容易出错。该语言的语义和编译器的类型检查机制将防止您意外地使用错误的索引访问数组。

不要忘记具有const正确性的例子-循环可以修改元素。这里的许多示例都没有这样做,应该使用cont迭代器。这里我们假设

class T {
  public:
    T (double d) : _d { d } {}
    void doSomething () const { cout << _d << endl; return; }
    void changeSomething ()   { ++_d; return; }
  private:
    double _d;
};

vector<T> v;
// ...
for (const auto iter = v.cbegin(); iter != v.cend(); ++iter) {
    iter->doSomething();
}

还要注意,在c++ 11表示法中,默认是复制元素。使用引用来避免这种情况,和/或允许修改原始元素:

vector<T> v;
// ...
for (auto t : v) {
    t.changeSomething(); // changes local t, but not element of v
    t.doSomething();
}
for (auto& t : v) {      // reference avoids copying element
    t.changeSomething(); // changes element of v
    t.doSomething();
}
for (const auto& t : v) { // reference avoids copying element
    t.doSomething();      // element can not be changed
}
 //different declaration type
    vector<int>v;  
    vector<int>v2(5,30); //size is 5 and fill up with 30
    vector<int>v3={10,20,30};
    
    //From C++11 and onwards
    for(auto itr:v2)
        cout<<"\n"<<itr;
     
     //(pre c++11)   
    for(auto itr=v3.begin(); itr !=v3.end(); itr++)
        cout<<"\n"<<*itr;