Ralf Zhang
Ralf Zhang

Reputation: 181

C++ How to reverse the order of elements in vector?

This is my first ever post on this site as a C++ beginner. My question is rather simple. Write a function that reverse the order of elements in a vector. For example, 1, 3, 5, 7, 9 becomes 9, 7, 5, 3, I. The reverse function should produce a new vector with the reversed sequence, leaving its original vector unchanged.

And here is my code. When I run it there is nothing coming after the word "Printing". I am pretty sure I made a silly and simple mistake somewhere but just couldn't figure it out. Would appreciate any help.Cheers.

void reverse_a(const vector<int>&v1, vector<int>&v2)
{
    //this function creates vector2 with the reverse sequence of elements from vector 1


  for(int i=v1.size()-1;i<=0;--i)

  { 
      v2.push_back(v1[i]);

  }
}

void print(const vector<int>&v)
{
    cout<<"Printing"<<endl;
    for(int i=0;i<v.size();++i)
        cout<<v[i]<<",";
    cout<<"\n"<<"end of print.\n";
}

int main()
{
    vector<int>v1;
    vector<int>v2;
    int input;
    while(cin>>input)
        v1.push_back(input);
    reverse_a(v1,v2);

    print(v2);

    keep_window_open("`");

}

Upvotes: 2

Views: 22736

Answers (5)

paxdiablo
paxdiablo

Reputation: 881553

for(int i=v1.size()-1;i<=0;--i)
//                    ^^^^

That middle bit i <= 0 is the continuation clause and must be true for the loop to iterate. It won't ever be true unless your vector is empty or of size one, in which case you'll get an error when you try to access v1[-1].

Change the <= to a >=.


Mind you, I'm also not a big fan of passing in a vector (even as a reference) to be modified, since there's no guarantee to the function it won't already have something in it. I think it makes more sense to create the target vector new within the function and pass it back, something like:

#include <iostream>
#include <vector>
using namespace std;

vector<int> reverse_a (const vector<int> &v1) {
    vector<int> v2;
    size_t i = v1.size();
    while (i > 0)
        v2.push_back (v1[--i]);
    return v2;
}

void print (const vector<int> &v) {
    cout << "Printing" << endl;
    for (size_t i = 0; i < v.size(); ++i)
        cout << v[i] << ",";
    cout << "\nEnd of print.\n";
}

int main (void) {
    int input;
    vector<int> v1;
    while (cin >> input)
        v1.push_back (input);

    vector<int> v2 = reverse_a (v1);
    print (v2);

    return 0;
}

You'll also notice I've changed to using size_t as the index type and made adjustments to ensure it doesn't go negative.


This is all assuming, of course, that you're trying to learn relatively simple concepts of programming. Professional C++ programmers would probably use an iterator to populate a new vector, along the lines of:

vector<int> reverse_a (vector<int> &v1) {
    vector<int> v2;
    vector<int>::iterator it = v1.end();
    while (it != v1.begin())
        v2.push_back (*(--it));
    return v2;
}

or with the minimalist (no function call needed other than the standard library ones):

vector<int> v2 (v1.rbegin(), v1.rend());

Once you've committed to learning C++, you should do so with gusto. There's nothing quite so bad as a half-convert to the language :-)

Upvotes: 8

Robert Mutke
Robert Mutke

Reputation: 2929

Use algorithm reverse. It takes bidirectional iterators, so you pass begin() and end():

int main(void)
{
    std::vector<int> v{1, 2, 3, 4};
    std::cout << "vector: ";
    for (int i: v)
      std::cout << i << ", ";
    std::cout << "\n";
    std::reverse(v.begin(), v.end());
    std::cout << "reversed vector: ";
    for (int i: v)
      std::cout << i << ", ";
    std::cout << "\n";

    return 0;

}

If you need a copy, then go for: reverse_copy

Upvotes: 1

TNA
TNA

Reputation: 2745

std::vector<int> reverse(std::vector<int>v)
{
  std::reverse(v.begin(),v.end());
  return v;
}

Upvotes: 9

Jarod42
Jarod42

Reputation: 217293

You confound <= with >=.

But using reverse_iterator would make the job simpler

void reverse_a(const std::vector<int>&v1, std::vector<int>&v2)
{
    v2.clear();
    for (std::vector<int>::const_reverse_iterator it = v1.rbegin(); it != v1.rend(); ++it) {
        v2.push_back(*it);
    }
}

Note: it is a good place to use auto (in C++11) instead of the long type here:

for (auto it = v1.rbegin(); it != v1.rend(); ++it)

And the code can even be simplified to:

void reverse_a(const std::vector<int>&v1, std::vector<int>&v2)
{
    v2.assign(v1.rbegin(), v1.rend());
}

Upvotes: 0

Varun Gupta
Varun Gupta

Reputation: 1

You can try swapping the values using the iterator.

Something like :

Iterator first = vec.begin();
Iterator last = vec.end();

while ((first!=last)&&(first!=--last)) 
{
    std::iter_swap (first,last);
    ++first;
}

Upvotes: -1

Related Questions