c++:如何在每次打印向量时打印向量元素的索引?

v8wbuo2f  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(144)

我有一个船只的向量,我需要访问这些船只并定期修改它们(即删除它们),所以如果我能打印它们的索引沿着所有其他信息,那就太好了,但我似乎不知道怎么做。
最接近的方法是使用一个简单的for循环,但随着向量大小的增加,最终会打印当前索引沿着之前的索引(因为我的i是〈vector.size())

vector <Boat> berths_reg; 

//print vector elements info
void Boat::print_info()
{
    cout << endl;
    for(int i = 0; i < berths_reg.size(); i++)
    {
        cout << "Index       : " << i << endl;
    }
    cout << "Boat type   : " << type << endl;
    cout << "Boat length : " << length << endl;
    cout << "Draft depth : " << draft << endl;
    cout << endl;
}

//iterate through vector to print all elements
void print_vector() 
{
    vector <Boat> ::iterator it;

    for (it = berths_reg.begin(); it != berths_reg.end(); ++it)
    {
        it->print_info();
    }
}

//Storing boats (objects data) inside vector
void add_boat(Boat* b, string type, int length, int draft)
{
    b->get_type(type);
    b->get_length(length);
    b->get_draft(draft);
    berths_reg.push_back(*b);
}
b5buobof

b5buobof1#

只需在同一个循环中同时打印索引和信息:

void print_vector() 
{
  for(int i = 0; i < berths_reg.size(); ++i)
  {
    cout << "Index       : " << i << endl;
    berths_reg[i].print_info();    
  }
}
wqnecbli

wqnecbli2#

用基于范围的循环来实现:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> myVector = {10, 20, 30, 40, 50};

    // Print vector elements with their indexes
    int i = 0;
    for (auto &element : myVector) {
        cout << "Index " << i++ << ": " << element << endl;
    }

    return 0;
}

相关问题