试图了解-Wsign-conversion错误

时间:2015-02-28 05:26:42

标签: c++ c++11

我有以下示例程序,它给出了一个错误:

error: conversion to ‘__gnu_cxx::__normal_iterator<long unsigned int*, std::vector<long unsigned int> >::difference_type {aka long int}’ from ‘std::size_t {aka long unsigned int}’ may change the sign of the result [-Werror=sign-conversion] for (auto iter = v.begin(); iter != v.begin() + pos; ++iter) { ^ cc1plus: all warnings being treated as errors

如果我用-Wsign-conversion编译它,即: g++ ./test.cpp -std=c++11 -Wsign-conversion

源:

#include <vector>
#include <iostream> 

int main() {
    std::vector<std::size_t> v;
    for (std::size_t i = 0; i < 10; ++i) {
        v.push_back(i);
    }

    std::size_t pos = 4;

    for (auto iter = v.begin(); iter != v.begin() + pos; ++iter) {
        std::cout << *iter << " ";
    }

    return 0;
}

你能解释为什么这是一个错误,我该如何处理它?谢谢。

更新: 如果我有以下情况怎么办?

#include <vector>
#include <iostream> 

static bool someCondition(std::size_t i) {
    return true; //just in case
}

int main() {
    std::vector<std::size_t> v;

    for (std::size_t i = 0; i < 20; ++i) {
        v.push_back(i);
    } 

    // I have some initial counter value
    std::size_t candidatesIndex = 0;

    // later I refill the vector somehow if some condition is true for the particular vector's index
    for (std::size_t i = 0; i < 5; ++i) {

        if (someCondition(i)) {

            if (candidatesIndex >= v.size()) {
                v.push_back(i);
            } else {
                v[candidatesIndex] = i; 
            }

            ++candidatesIndex;  
        }
    }

    //now the vector contains 20 items, but I am interested only in the first 5 ones
    //and my candidatesIndex gives me that information (i.e. it equals to 5, not 20)
    std::cout << candidatesIndex << " " << v.size() << std::endl; // 5 20

    //now I want to iterate through the first 5 calculated values (where 5 is my candidatesIndex) 
    //and perform some logic    
    for (auto iter = v.begin(); iter != v.begin() + candidatesIndex; ++iter) {
        std::cout << *iter << " ";
    }

    return 0;
}

我应该如何宣布我的candidatesIndex去除警告?

0 个答案:

没有答案
相关问题