我已经告诉别人,编写using namespace std;代码是错误的,我应该用std::cout和std::cin直接代替.
为什么被using namespace std;认为是不好的做法?是低效还是冒着声明模糊变量(与名称std空间中的函数具有相同名称的变量)的风险?它会影响性能吗?
我在我的代码中发布了一个问题,其唯一的#include指令如下:
#include <bits/stdc++.h>
Run Code Online (Sandbox Code Playgroud)
我的老师告诉我这样做,但在评论部分,我被告知我不应该这样做.
为什么?
c++ portability c++-faq turbo-c++ implementation-defined-behavior
如果将数组传递给另一个函数(未传递大小),是否可以确定数组的大小?该数组初始化为int array [] = {XXX} ..
我知道不可能做sizeof,因为它会返回指针的大小.我问的原因是因为我需要在传递数组的其他函数内运行for循环.我尝试过类似的东西:
for( int i = 0; array[i] != NULL; i++) {
........
}
Run Code Online (Sandbox Code Playgroud)
但我注意到在数组的近端,array [i]有时包含像758433这样的垃圾值,这不是数组初始化中指定的值.
所以我的 C++ 老师在课堂上告诉我们,C++ 中没有确定数组大小的函数,我对此并不满意。我在 stackoverflow 上发现了一个问题,给出了这段代码(sizeof(array)/sizeof(*array)),虽然我不太明白它,但我知道它需要分配给数组的内存总量,并将其除以我假设的其默认内存分配数据类型...(???) 我决定练习编写函数(我在 CS 111 - 基础知识 1)并编写一个函数,该函数返回我传递给它的任何数组中的元素数量。这是我写的:
#include <iostream>
using namespace std;
int length_of_array(int some_list[])
{
// This only returns the integer 1 for some reason
return (sizeof(some_list)/sizeof(*some_list));
}
int main()
{
// Declare and initialize an array with 15 elements
int num_list[] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30};
//Outputs what I assume is the total size in bytes of the array
cout << sizeof(num_list) << endl;
//Outputs what I assume to be size of memory set …Run Code Online (Sandbox Code Playgroud) c++ ×5
arrays ×3
c++-faq ×2
pointers ×2
c ×1
implementation-defined-behavior ×1
namespaces ×1
null ×1
portability ×1
std ×1
turbo-c++ ×1