简体   繁体   English

如何迭代向量

[英]How do I iterate vector

I have such a code我有这样的代码

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void removeFirstFromVec(vector<int> & vecLink) {
    // remore first element from some vector
    vecLink.erase(vecLink.begin() + 0);
}

int main()
{
    vector<int> myVec;
    myVec.push_back(1);
    myVec.push_back(2);
    myVec.push_back(3);
    cout << "Before removal\n";
    for (auto & i : myVec) {
        cout << myVec[i-1] << endl;
    }
    removeFirstFromVec(myVec);
    cout << "After removal\n";
    for (auto & i : myVec) { // starts with 2
        cout << myVec[i-1] << endl;
    }
    return 0;
}

But on the place where I put a comment it starts with 2 instead of 0 and it causes an error.但是在我发表评论的地方,它以 2 而不是 0 开头,这会导致错误。 What I've done wrong or is there a way to use something brief like auto & i: myVec instead of for (int i = 0; i <...size(); i++) without such an error我做错了什么,或者有没有办法使用类似auto & i: myVec而不是for (int i = 0; i <...size(); i++)之类的简短内容而不会出现此类错误

In the range-based for loop在基于范围的 for 循环中

for (auto & i : myVec) {
    cout << myVec[i-1] << endl;
}

i is the element of the vector, not the index. i是向量的元素,而不是索引。 It should be它应该是

for (auto & i : myVec) {
    cout << i << endl;
}

Iteration returns the items themselves, not indices.迭代返回项目本身,而不是索引。

vector<int> vec { 5, 3, 2 };
for (int i: vec) {
  cout << i << endl;
}

Will output this:请问output这个:

5
3
2

If you do the following:如果您执行以下操作:

  1. Use templated-function to accept any type for the vector.使用模板函数接受向量的任何类型。

  2. Use direct initialization method rather than push_back() to avoid huge number of lines.使用直接初始化方法而不是push_back()以避免大量行。

  3. Braces for single syntax is optional.单一语法的大括号是可选的。 Avoid it to reduce confusion during coding complex programs.在编写复杂程序时避免使用它以减少混淆。

Then you can write the same code in a better manner (don't forget the comments):然后您可以以更好的方式编写相同的代码(不要忘记注释):

#include <iostream>
#include <vector>

using namespace std;

// defining a templated-function
template<class T>
void removeFirstFromVec(vector<T>& vecLink) {
    vecLink.erase(vecLink.begin());
}

int main(void) {
    // initializing with direct-initialization method
    vector<int> myVec {1, 2, 3};

    cout << "Before removal\n";

    // no braces
    for (auto& i : myVec)
        // 'i' isn't an index here, it's an element
        cout << i << endl;

    removeFirstFromVec(myVec);

    cout << "After removal\n";

    // no braces    
    for (auto& i : myVec)
        cout << i << endl;

    return 0;
}

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

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