Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

c++ - how to set or initialize default value for all elements of a table or 2d array or multdimentional array

I want to set a default nonzero value for all elements of a table or 2d array. array[size]={12} sets first elements only 12 and others are all 0 in a row.But fill(array,array+size,12) sets all elements to 12 in a row only.I could't apply this for 2d array.Is there any way to do this using fill() or any way without direct initialization using double for loop

#include <iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
using namespace std;

int main()
{
   int arra[10][10];//declare 2d array

  for(int k=0;k<10;k++)//takes k's value 10 for 10 rows
     fill(arra,arra+10,45);//select a row and set all columns to 45 didn't work

}

array initialization http://www.fredosaurus.com/notes-cpp/arrayptr/array-initialization.html

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For C arrays, you'll probably want to use memset. You've marked this as C++, though, so I feel obliged to give a C++ answer:

std::vector<std::vector<int>> v(10, std::vector<int>(10, 45));

This creates a std::vector of 10 std::vector<int>s of size 10 with each element initialized to 45.

See here for the ideone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...