简体   繁体   English

C ++如何反转向量中元素的顺序?

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

This is my first ever post on this site as a C++ beginner. 这是我作为C ++初学者在本网站上发表的第一篇文章。 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. 例如,1,3,5,7,9变为9,7,5,3,I。反向函数应产生具有反向序列的新向量,使其原始向量保持不变。

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("`");

}
std::vector<int> reverse(std::vector<int>v)
{
  std::reverse(v.begin(),v.end());
  return v;
}
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. 中间位i <= 0continuation子句,对于循环迭代必须为true 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] . 除非你的向量为空或大小为1,否则它将永远不会成立,在这种情况下,当你尝试访问v1[-1]时会出现错误。

Change the <= to a >= . <=更改为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. 您还会注意到我已更改为使用size_t作为索引类型并进行了调整以确保它不会变为负数。


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: 专业的C ++程序员可能会使用迭代器来填充新的向量,包括:

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. 一旦你致力于学习C ++,你就应该热情地学习。 There's nothing quite so bad as a half-convert to the language :-) 没有什么比半语言转换更糟糕了:-)

Use algorithm reverse . 使用算法reverse It takes bidirectional iterators, so you pass begin() and end() : 它需要双向迭代器,因此您传递begin()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 如果您需要副本,请转到: reverse_copy

You confound <= with >= . 你混淆<= with >=

But using reverse_iterator would make the job simpler 但是使用reverse_iterator可以使工作更简单

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: 注意:这是一个使用auto (在C ++ 11中)而不是long类型的好地方:

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());
}

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;
}

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

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