问题
I am new to c++ . I was trying to write following code to fill up each byte of array with new values without overriding others. Each byte (r) below should be added up at new address of the array.
int _tmain(int argc, _TCHAR* argv[]) {
char y[80];
for(int b = 0; b < 10; ++b) {
strcpy_s(y, "r");
}
}
Please let me know if there is any function in c++ which can do that. In the above case the value 'r' is arbitrary and this can have any new value. So the resultant array of characters should contain value rrrrr... 10 times. Thanks a lot in advance for this.
回答1:
Using C++11
#include <algorithm>
#include <iostream>
int main() {
char array[80];
std::fill(std::begin(array),std::begin(array)+10,'r');
}
Or, as mentioned in the comments you can use std::fill(array,array+10,'r')
.
回答2:
You can use the []
operator and assign a char
value.
char y[80];
for(int b=0; b<10; ++b)
y[b] = 'r';
And yes, std::fill
is a more idiomatic and modern C++ way to do this, but you should know about the []
operator too!
回答3:
// ConsoleApp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int fun(bool x,int y[],int length);
int funx(char y[]);
int functionx(bool IsMainProd, int MainProdId, int Addons[],int len);
int _tmain(int argc, _TCHAR* argv[])
{
int AddonCancel[10];
for( int i = 0 ; i<4 ;++i)
{
std::fill(std::begin(AddonCancel)+i,std::begin(AddonCancel)+i+1,i*5);
}
bool IsMainProduct (false);
int MainProduct =4 ;
functionx(IsMainProduct,MainProduct,AddonCancel,4);
}
int functionx(bool IsMainProd, int MainProdId, int Addons[],int len)
{
if(IsMainProd)
std::cout<< "Is Main Product";
else
{
for(int x = 0 ; x<len;++x)
{
std::cout<< Addons[x];
}
}
return 0 ;
}
回答4:
Option 1:
Initialize the array while defining. Convenient for initializing only a small number of values. Advantage is that the array can be declared const
(not shown here).
char const fc = 'r'; // fill char
char y[ 80 ] = { fc, fc, fc, fc,
fc, fc, fc, fc,
fc, fc };
Option 2: Classic C
memset( y, y+10, 'r' );
Option 3: Classic (pre-C++11) C++
std::fill( y, y+10, 'r' );
来源:https://stackoverflow.com/questions/14446850/filling-up-an-array-in-c