简体   繁体   中英

How to access different members of vector in a function

#include <vector>

int main()
{
   vector <class> abc;
}

when pressing some key

vector.push_back(class());

each loop

draw(vector)// what should the parameters be?

draw function

draw(vector,sizeofvector)
{
    for (int x=0;x< sizeofvector;x++)
    {draw vector[x];}
}

how should the parameters look? should i be passing an *abc?

In modern C++ this can be answered without correcting your errors:

for (const auto & x : vector) { draw(x); }

Alternatively (still in C++11):

for (auto it = vector.cbegin(), end = vector.cend(); it != end; ++it)
{
  draw(*it);
}

This might work in C++98/03, too:

for (std::size_t i = 0, end = vector.size(); i != end; ++i) { draw(vector[i]); }

If you don't intend to modify the vector, you usually pass it by const reference.

void draw(const std::vector<T>& v)
{
    for (int x = 0; x < v.size(); x++)
    {
        // draw v[x];
    }
}

You can also use iterators (this is often preferable).

void draw(const std::vector<T>& v)
{
    for (std::vector<T>::const_iterator x = v.begin(); x != v.end(); ++x)
    {
        // draw *x;
    }
}

The reason you don't pass it by value ( draw(std::vector<T> v) ) is because that would cause the entire vector to be copied every time you call the function, which is obviously incredibly inefficient. References mean that you just refer to the existing vector rather than creating a new one.

std::vector is the type. You need to pass in an instance, so in your case:

draw(abc);

I also agree that your function should have prototype:

void draw( const std::vector<class> & v );
#include <algorithm>
#include <vector>
#include <iostream>

void addOne(int& value)
{
    value++;
}

void print(int& value)
{
    std::cout << value;
}

int main()
{
    std::vector<int> myVector;
    myVector.push_back(1);
    myVector.push_back(2);
    myVector.push_back(3);
    std::for_each(myVector.begin(), myVector.end(), addOne);
    std::for_each(myVector.begin(), myVector.end(), print);
}

Output: 234

wrote by hand, compiler errors possible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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