Question

C++ question. Introduce a pass by pointer function that reverses a whole vector.

C++ question.

Introduce a pass by pointer function that reverses a whole vector.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>
#include <vector>

using namespace std;

void printVector(const vector<int> &v) {
    for (size_t i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
    cout << endl;
}

void reverse(vector<int> *v) {
    int temp;    // temp variable for swapping data
    for (int i = 0; i < v->size() / 2; ++i) {    // iterate until half of the array
        temp = (*v)[i];
        (*v)[i] = (*v)[v->size() - i - 1];
        (*v)[v->size() - i - 1] = temp;    // swap
    }
}

int main() {
    vector<int> v = {1, 4, 9, 16, 9, 7, 4, 9, 11};
    cout << "Original vector: ";
    printVector(v);
    reverse(&v); // reverse the vector
    cout << "Reversed vector: ";
    printVector(v);
    return 0;
}

Add a comment
Know the answer?
Add Answer to:
C++ question. Introduce a pass by pointer function that reverses a whole vector.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT