初学者来自程序员.我需要复制切片(以及底层数组的一部分),这样调用者就不会改变数组的原始元素.我想我可以编写一个函数来为特定类型的数组执行此操作:
func duplicateSliceOfSomeType(sliceOfSomeType []SomeType) []SomeType {
dulicate := make([]SomeType, len(sliceOfSomeType))
copy(duplicate, sliceOfSomeType)
return duplicate
}
Run Code Online (Sandbox Code Playgroud)
但有没有办法一般地创建相同的方法,也许没有泛型?
func duplicateSlice(slice []?) []?{
duplicate := make([]?, len(slice))
copy(duplicate, slice)
return duplicate
}
Run Code Online (Sandbox Code Playgroud) 在我维护的系统中,用户从基于1的索引方案中请求来自集合的元素.值存储在C++/C中基于0的数组中.
如果错误地输入0作为此函数的输入,以下假设代码是否可移植?在将基于1的编号方案转换为基于0的编号方案时,是否有更好的方法来验证用户的输入?
const unsigned int arraySize;
SomeType array[arraySize];
SomeType GetFromArray( unsigned int oneBasedIndex )
{
unsigned int zeroBasedIndex = oneBasedIndex - 1;
//Intent is to check for a valid index.
if( zeroBasedIndex < arraySize )
{
return array[zeroBasedIndex];
}
//else... handle the error
}
Run Code Online (Sandbox Code Playgroud)
我的假设是(unsigned int)( 0 - 1 )总是大于arraySize; 这是真的?
正如一些人在下面的答案中建议的那样,另一种方法是检查oneBasedIndex并确保它大于0:
const unsigned int arraySize;
SomeType array[arraySize];
SomeType GetFromArray( unsigned int oneBasedIndex )
{
if( oneBasedIndex > 0 && oneBasedIndex <= arraySize ) …Run Code Online (Sandbox Code Playgroud) 当我遇到以下错误键入的代码时,我正在调试程序,类似于以下内容:
//Original (wrong)
std::string first("Hello");
std::string second = first + second;
//Instead of this (correct)
std::string first("Hello");
std::string second = first + something_else;
Run Code Online (Sandbox Code Playgroud)
显然我并没有尝试这样做(我想不出为什么有人会想这样做),但它让我思考.它看起来不像原版应该工作,我认为它是未定义的.实际上,这是我问题的根源.
要使问题更加通用,请考虑以下事项:
SomeType a;
SomeType b = a + b;
Run Code Online (Sandbox Code Playgroud)
行为是否未定义仅仅是因为b尚未初始化(请参阅此答案)?
如果行为未定义,那么我真正的问题是,为什么?
对于某些标准容器,这只是未定义的std::string,或者是否在更一般意义上未定义(STL类,用户定义的类,POD,基本类型)?
该标准的哪一部分适用于此?
如果需要,假设这是c ++ 11.
我正在修改一个接受const char*并使用函数ProcessString的函数.ProcessString是一个函数,它期望以null结尾的字符缓冲区作为char*.缓冲区中的字符可能会也可能不会被修改,如下面的函数签名所定义.为了"弥合差距",我使用临时的std :: string:
void ProcessString( char* str );
void SomeFunction( const char* str )
{
string temp(str);
ProcessString( &temp[0] );
}
Run Code Online (Sandbox Code Playgroud)
我的主要问题是关于std :: string :: operator []的保证以及上面&temp [0]返回的地址是否是一个可用的,以null结尾的缓冲区作为char*.其次,其次,还有更好的方法吗?
我正在使用C++ 03.