c++ - cpp新手问题: error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result

标签 c++ arrays

我正在尝试为数组实现我自己的交换函数,但它似乎存在转换问题。 我不知道。 如果这个问题太愚蠢,请原谅我。

这是源代码:

x_quiz3.h

#include<array>

using namespace std;

void swap_arr_element(array<int,5> &arr, int index1, int index2){
    int temp{arr.at(index1)};
    arr.at(index1) = arr.at(index2);
    arr.at(index2) = temp;
}

void start_x_quiz3(){
    array arr{1,2,4,3,5};
    swap_arr_element(arr, 2, 3);
    for (auto &i : arr){
        cout << i << " ";
    }
}

主要.cpp:

#include <iostream>
#include "x_quiz3.h"

int main()
{
    start_x_quiz3();
    return 0;
}

错误信息:

||=== Build: Debug in chapter6 (compiler: GNU GCC Compiler) ===|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h||In function ‘void swap_arr_element(std::array<int, 5>&, int, int)’:|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h|8|error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h|9|error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h|9|error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]|
/home/lewisluk/CodeBlocksProjects/tutorials/quizs/chapter6/x_quiz3.h|10|error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

最佳答案

at 的参数函数是 size_type,它是一个 unsigned 类型。

交换函数的索引参数是int,它是一个有符号类型。

编译器说它不能安全地从有符号类型转换为无符号类型(它不能,想想如果你提供负索引会发生什么)。

简单的解决方案是使交换函数索引参数也无符号,最好使用size_t 类型:

void swap_arr_element(array<int,5> &arr, size_t index1, size_t index2){ ... }

关于c++ - cpp新手问题: error: conversion to ‘std::array<int, 5>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59662985/

相关文章:

arrays - 我想从解析加载数组数据(快速)

javascript - 数组中 2 个值之间的 "toggle"- JS

c++ - boost :将基础类(class)替换为标准类(class)?

c++ - 使用 automake 构建 gSoap 应用程序时的不同行为

c++ - 双端队列内存分配可以稀疏吗?

c++ - C 字符串到宽 C 字符串赋值

c++ - 如何检测 Asio 库的死锁?

c - 关于使用数组乘以 C 中的多项式

ios - 用另一个字典替换数组中的字典

mysql - 是否可以使用mysql脚本获取列表对象的数据?