我需要澄清一下有关C++中指针初始化基础知识的概念.根据我的理解,在使用指针输入一些值之前,必须为指针分配一个地址.
int *p;
*p=10; //inappropriate
cout << *p <<"\n";
Run Code Online (Sandbox Code Playgroud)
这可能会显示正确的输出(10),但这可能会导致较大的程序出现问题,因为p最初有垃圾地址,可以是任何东西,以后可能会在程序的其他地方使用.所以,我认为这是不正确的,正确的方法是:
int *p;
int x=10;
p=&x; //appropriate
cout << *p <<"\n";
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果上述理解是正确的,那么同样适用于char*吗?:
const char *str="hello"; // inappropriate
cout << str << "\n";
//OR
const string str1= "hello";
const char str2[6] ="world";
const char *str=str1; //appropriate
const char *st=str2; //appropriate
cout << str << st << "\n";
Run Code Online (Sandbox Code Playgroud)
请指教
假设我有一节课:
class sampleVector
{
public:
int a;
int b;
string c;
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个带有多个sampleVector对象的向量,但是向量有2个(多个)连续的sampleVector对象,它们具有相同的a(例如5)和b(比如10).
现在我想删除矢量中具有= 5和b = 10的所有sampleVector对象.
问题是,对于多次连续发生,下面是一种方法:
for (;it!=itEnd;it++)
{
if (it->getA() == 5 && it->getB() == 10)
{
vec.erase(it);
it=vec.begin(); // Resetting this is must
}
}
Run Code Online (Sandbox Code Playgroud)
但我想知道如何使用"删除",因为以下不起作用:
for (;it!=itEnd;it++)
{
if (it->getA() == 5 && it->getB() == 10)
{
vec2.erase(remove(vec2.begin(), vec2.end(), *it), vec2.end()); // doesn't even compile
}
}
Run Code Online (Sandbox Code Playgroud)
当我们有一个原始数据类型的向量时,我们可以使用这种方法去除,并且我们有一个需要删除的特定值.但是对于非原始数据类型的向量,我们如何通过传递迭代器而不是值来使用"remove"?
在Java中,Object类是所有类的基类.C++中是否还有这样的类?
我对这个问题的动机是:
try
{
if (something) throw int(a);
if (something) throw char(b);
if (something) throw float(c);
}
catch(...)
{
handle
}
Run Code Online (Sandbox Code Playgroud)
除此之外,还有其他方法可以使用单个catch块来处理所有这些异常吗?