【发布时间】:2016-06-19 13:05:53
【问题描述】:
所以我目前正在学习 C++(以前在 Java 和 JavaScript 方面有经验),就我而言,你不能像在 Java 中那样在 C++ 中将数组作为参数传递。但是您可以将指针传递给数组中的第一个元素。所以我可以像这样遍历一个数组:
bool occurs(int* arrInt, int length, int sought, int& occurrences)
{
for (int i = 0; i <= length; ++i)
{
if (arrInt[i] == sought)
occurrences++;
}
// if occurences > 0 return true, else false
return occurrences;
}
整个函数基本上应该返回一个布尔值,告诉我给定的 int (sought) 是否在数组 (arrInt) 中找到。我还通过参考 (occurrences) 提供了一个小计数器。
但让我烦恼的是length 参数。 C++11 提供了那些花哨的 std::begin / cbegin() 和 std::end / cend() 函数来获取数组的第一个和最后一个元素:
int arr[] = {1,2,3,4} // arr is basically a pointer to an int, just as the
// function parameter of ocurs(int*,int,int,int&)
auto end = std::end(arr); // end points to one past last element
但是为什么我不能使用我的arrInt 参数作为该函数的参数呢?然后我可以摆脱长度参数:
bool occurs(int* arrInt, int sought, int& occurences)
{
for (auto it = std::begin(arrInt); it != std::end(arrInt); ++it)
{
if (*it == sought)
occurences++;
}
// if occurences > 0 return true, else false
return occurences;
}
我在这里遗漏了一个主要概念吗?提前致谢
【问题讨论】:
-
@rettichschnidi 感谢您的链接,但我知道那个类,使用 vector
::iterator 太容易了,如果我没有选择矢量怎么办? :) -
然后 a) 在问题中说明这一点,然后 b) 看看 std::count
-
“我是否遗漏了一个重要概念?” - 是的。
std::vector为您做这件事。这是使用数组的面向对象的方式。你想要一个数组?使用向量。 -
@NiklasVest 听起来很有趣,但确实如此。根据标准,
std::vector管理一个 动态 数组。如果你使用像C这样的过程 语言,你必须记住指针和长度。面向对象的方法是将指针和长度存储在一个对象内——一个抽象数据类型。它可以执行除内部之外的所有操作。而且,因为C++所有的访问都是通过inline 被编译器完全剥离的琐碎函数。因此,它就像您以C方式完成所有操作一样快速。