for循环中的向量迭代器,返回语句,警告,c ++

Cry*_*tal 5 c++ iterator vector

关于C++的家庭作业,我有三个问题.目标是创建一个简单的回文方法.这是我的模板:

#ifndef PALINDROME_H
#define PALINDROME_H

#include <vector>
#include <iostream>
#include <cmath>

template <class T>
static bool palindrome(const std::vector<T> &input)
{
    std::vector<T>::const_iterator it = input.begin();
    std::vector<T>::const_reverse_iterator rit = input.rbegin();

    for (int i = 0; i < input.size()/2; i++, it++, rit++)
    {
        if (!(*it == *rit)) {
            return false;   
        }
    }
    return true;
}

template <class T>
static void showVector(const std::vector<T> &input)
{

    for (std::vector<T>::const_iterator it = input.begin(); it != input.end(); it++) {
        std::cout << *it << " ";
    }
}

#endif
Run Code Online (Sandbox Code Playgroud)

关于上面的代码,你可以在for循环的第一部分中声明多个迭代器吗?我尝试在palindrome()方法中定义"it"和"rit",并且在rit之前我一直收到关于需要","的错误.但是当我在for循环外部剪切和粘贴时,编译器没有错误.(我正在使用VS 2008).

第二个问题,我几乎只是在这个问题上大放异彩.但是我在palindrome()方法中使用return语句的方式好吗?在我的脑海中,我认为它的工作原理是,一旦*it和*rit彼此不相等,那么函数返回false,此时该方法退出.否则,如果它一直通过for循环,那么它在结束时返回true.如果我曾经在我的书中找到一个很好的例子并且找不到一个很好的例子,那么我完全放弃了返回语句如何工作的大脑.

最后,我得到了这个警告:

\palindrome.h(14) : warning C4018: '<' : signed/unsigned mismatch
Run Code Online (Sandbox Code Playgroud)

现在是因为我运行我的for循环直到(i <input.size()/ 2)并且编译器告诉我输入可能是负数?谢谢!

Cub*_*bbi 8

迭代器是家庭作业的要求吗?此任务可以简化为以下呼叫std::equal:

template <class T>
bool palindrome(const std::vector<T> &input)
{
        return equal(input.begin(), input.begin()+input.size()/2, input.rbegin());
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*lis 5

你可以在for循环的第一部分声明多个迭代器吗?

是的,但它们都必须属于同一类型,所以你不能同时声明a const_iterator和a const_reverse_iterator.

我在palindrome()方法中使用return语句的方式好吗?

是的,虽然为什么不进行比较*it != *rit

palindrome.h(14) : warning C4018: '<' : signed/unsigned mismatch
Run Code Online (Sandbox Code Playgroud)

i已签署; std::vector::size()返回无符号值.如果i未签名,则不会收到此警告.

但是作为一个建议:使用两个前向迭代器可能更简单.初始化一个到.begin()另一个到.end() - 1.然后你可以递增第一个并递减第二个,你的循环测试就变成了it1 < it2.类似于以下(完全未经测试的)for循环:

for (iterator it1(v.begin()), it2(v.end() - 1); it1 < it2; ++it1, --it2)
Run Code Online (Sandbox Code Playgroud)

这样你就不再需要单独的i计数器和比较了; 一切都是用迭代器完成的.