我不熟悉c++语言。我已经开始使用向量,并注意到在我看到的所有通过索引遍历向量的代码中,for循环的第一个参数总是基于向量的值。在Java中,我可以对数组列表做这样的事情:
for(int i=0; i < vector.size(); i++){
vector[i].doSomething();
}
我在c++中看不到这个的原因是什么呢?这是不好的做法吗?
我不熟悉c++语言。我已经开始使用向量,并注意到在我看到的所有通过索引遍历向量的代码中,for循环的第一个参数总是基于向量的值。在Java中,我可以对数组列表做这样的事情:
for(int i=0; i < vector.size(); i++){
vector[i].doSomething();
}
我在c++中看不到这个的原因是什么呢?这是不好的做法吗?
当前回答
不要忘记具有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
}
其他回答
这是一个更简单的方法来迭代和打印值在向量。
for(int x: A) // for integer x in vector A
cout<< x <<" ";
int main()
{
int n;
int input;
vector<int> p1;
vector<int> ::iterator it;
cout << "Enter the number of elements you want to insert" << endl;
cin >> n;
for (int i = 0;i < n;i++)
{
cin >> input;
p1.push_back(input);
}
for(it=p1.begin();it!=p1.end();it++)
{
cout << *it << endl;
}
//Iterating in vector through iterator it
return 0;
}
迭代器的常规形式
正确的做法是:
for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
it->doSomething();
}
其中T是向量中类的类型。例如,如果类是CActivity,只需写CActivity而不是T。
这种类型的方法将适用于每个STL(不仅仅是向量,这是更好的一点)。
如果你仍然想使用索引,方法是:
for(std::vector<T>::size_type i = 0; i != v.size(); i++) {
v[i].doSomething();
}
//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;
如果你使用
std::vector<std::reference_wrapper<std::string>> names{ };
不要忘记,当你在for循环中使用auto时,也要使用get,就像这样:
for (auto element in : names)
{
element.get()//do something
}