函数中数组大小的Cpp我的索引变量有错误



我正试图在C++中的main外部创建一个函数,以搜索数组中是否存在元素,如果存在,该函数应将该元素在该数组中的索引/位置存储在另一个名为index的数组中。

问题是,当我尝试对两个数组使用相同的大小时,搜索函数告诉一个错误,其中大小变量必须是常数值,所以我尝试了,这是我的代码。。

#include <iostream>
using namespace std;
int searchForElement(int[], int const, int);
int main()
{
int array[5];
for (int i = 0; i < 5; i++)
array[i] = i * 2;

searchForElement(array, 5, 6);
return 0;
}
int searchForElement(int a[], int const n, int x) {
int index[n];
int ii = 0; //counter for index array

for (int i = 0; i < n; i++) {
if (a[i] == x){
index[ii] = i;
ii++;
}
}
return index[n];
}

严重性代码描述项目文件行禁止显示状态错误(活动(E0028表达式必须具有常量值ConsoleApplication1 C:。。。\repos\ConsoleApplication1\ConsoleApplication1\ConsoleAApplication1.cpp 45

如何使索引数组与此函数的任何给定数组大小相同

如何使索引数组与此函数的任何给定数组大小相同?

选项1:用函数模板替换函数,并使数组的大小成为模板参数。模板参数是编译时常数。

选项2:创建一个动态数组。最方便的方法是使用CCD_ 1。

选项3:不在searchForElement中创建数组。调用者知道他们需要多大的数组,所以你可以让他们把它传递到函数中,就像传递搜索数组一样。


return index[n];

首先,索引n将在数组的边界之外,因此程序的行为将是未定义的。其次,如果你的意图是搜索所有的索引,那么返回其中一个索引可能不是你想要做的

难道你不想利用一些现代功能让你的工作更轻松吗?

检查一下(需要C++20(:

#include <iostream>
#include <vector>
#include <span>

std::vector< std::size_t > searchForElement( const std::span<const int> array, const int key )
{
std::vector< std::size_t > indices;
indices.reserve( array.size( ) );

for ( std::size_t idx { }; idx < array.size( ); ++idx )
{
if ( array[idx] == key )
{
indices.push_back( idx );
}
}
indices.shrink_to_fit( );
return indices;
}
int main( )
{
std::array<int, 5> array;
for ( std::size_t idx { }; idx < std::size( array ); ++idx )
array[ idx ] = idx * 2;
std::vector< std::size_t > indices { searchForElement( array, 6 ) };
std::cout << "The given 'key' was found in indices:n";
for ( const auto index : indices )
{
std::cout << index << ' ';
}
}

摘要:

  1. 使用类似std::array的STL容器
  2. 返回包含索引的std::vector
  3. 使用std::span代替数组指针+大小。通过这种方式,您可以向其传递std::vectorstd::array原始数组

最新更新