How can I create a copy of a nested List in dart? In this code changes I make to the copy are also changed in the original
List board = [[0,0,0], [0,0,0], [0,0,0]];
List boardCopy = List.from(board); // create copy of the board
boardCopy[0][0] = 1; // change copy
print(board); // print original board
OUTPUT:
[[1,0,0], [0,0,0], [0,0,0]] <-- it has changed the original board!!!
I worked it out:
List boardCopy = board.map((element) => List.from(element)).toList();
Related
I am using arguments method in Navigator to pass a List
Navigator.pushNamed(context, '/cam', arguments: {'label' : list});
list is a string of items separated by comma for eg: item1, item2
and on receiving the the map of data from the first screen in second screen, I store that in a List by
data = ModalRoute.of(context).settings.arguments;
print(data);
rekognition.add(data['label']);
print(rekognition);
under Widget build and the above print statements prints [null, item1, item2] and [null, item1, item2, null, item1, item2] respectively.
this is where the problem is I don't why null pop up here and the list adds all the items second time
also
for (x=0; x<ing.length; x++) {
list = '$list , ${ing[x]}';
}
ing is again a list and its equal to List<dynamic>();
all I wanted to do was send a list of items which is added in the first screen and or else a empty list to the second screen and add all those received data to another variable in second screen and do object detection and add the label to the list of items that was passed form the first screen and go back to the first screen again with data of the all the list items including the data that was passed and added
I was able to solve null error by sending the list ing as a single variable instead of a map by
arguments: ing.toList() and the reason why the list in second screen adding items second time because of setState() function which on calling will rebuild the full widget tree hence my function of adding the items to list is called again, this was solved by a if condition
if (mylist.length == 0 ) { mylist.add(data); }
I have a unordered_map with key as string and value as list of string. I am able to figure out how to add elements to the list (which is a value to a specific key in the unordered map). What I am not able to figure out is how to remove elements from the same list.
Key parts of the code are:
Matrix is a basically imitating a pair of src and dest. Where I am trying to organize it to map where key is a unique src and the dest is collected in the value list.
Ex: [[A,B],[A,c]] -> {A:[B,C]}
vector<vector<string>>& matrix;
unordered_map<string, list<string>> um;
for (vector<string> mat: matrix) {
src = mat[0];
dst = mat[1];
if (um.find(src) == um.end()) {
um[src] = list<string>();
}
um[src].push_back(dst);
}
Above code seems to work as desired
To delete this is what I am doing
The unordered map can be something like this
{
A:[B,C],
C: [B],
B: [A,C]
}
The logic for below snippet is to start with A, pop B from list as value for key A. Use B, which is pop'ed from A's value list and find list which is value for key B and pop first element from it. Which happens to be A. So now use A as key to find the its value list and pop the next un-pop'ed element C, but to my surprise although I tried to pop B from list of key A when its still there.
Map is essentially a adjacency matrix of a cyclic graph where I am trying to delete/remove the edges one by one, but my question is specific to the syntax/code here.
string starting_src_key = "A";
string temp_str;
list<string> &templ = um[starting_src_key];
while(!templ.empty()) {
temp_str = templ.front();
cout << "\n" << temp_str;
templ.pop_front();
templ = um[temp_res];
}
I have tried various things like instead of &templ as variable I tried with just templ too (no & sign) but that didn't work either.
I am new to C++ so trying to understand a bit about map and list.
You cannot re-seat a reference, so templ = um[temp_res]; doesn't do what you expect. Use a pointer instead.
list<string> * templ = & um[starting_src_key];
while(!templ -> empty()) {
temp_str = templ -> front();
cout << "\n" << temp_str;
templ -> pop_front();
templ = & um[temp_res];
}
I'm creating a linked list of state objects, each of which contains a linked list of resident objects who live in that state. The user reads in a database file and then can choose from a handful of commands, such as finding a person, moving a person, or merging two states into a brand-new state. When I try to merge the people of 2 states, I have to create a new state, move all of the people from the first state's resident list to the new state's resident list and do the same with the resident list of the second state. The people should then appear in the new state's resident list but not in the resident lists of the original states. I'm getting a bunch of errors: when I try merging, I get repetitive free chunk warnings; when the user tries to print out the new state's resident list as a command, no one is listed; further, when the user tries to print either of the original states' resident lists, the first few are printed but then there's a set fault, the core gets dumped, and the program stops running. Any help would be greatly appreciated.
In my list object:
void addLink (Link <type> * data) {
if (first == NULL) {
first = data;
last = data;
}
else {
last->next = data;
last = data;
}
}
And in my main, if the command typed was "merge"...
else if (cmd == "merge") {
string state1, state2, newstate;
cin >> state1 >> state2 >> newstate;
State * ns = state_ls->addLink(new State(newstate))->data;
Link <State*> * s1 = searchList(state1, state_ls);
Link <State*> * s2 = searchList(state2, state_ls);
List <Person*> people1 = s1->data->res_list;
List <Person*> people2 = s2->data->res_list;
List <Person*> newres_list = ns->res_list;
Link <Person*> * temp = people1.first;
while (temp != NULL) {
newres_list.addLink(temp);
temp = temp->next;
}
temp = people2.first;
while (temp != NULL) {
newres_list.addLink(temp);
temp = temp->next;
}
}
A few issues in your code which could be the cause of your problems:
You don't check the result of searchList(). What if the state you enter doesn't exist and it returns NULL? Similarly for addLink() if it can fail.
people1, people2 and newres_list are copies of the original lists. Depending on how these classes are implemented this can be bad or very bad. You probably want to use pointers or references here, like:
List <Person*>& people1 = s1->data->res_list;
List <Person*>& people2 = s2->data->res_list;
List <Person*>& newres_list = ns->res_list;
If you wish to move persons from the original states to the new state you need to reset the person list head/tail after you move them. Probably something like:
s1->person->data->res_list->first = NULL;
s1->person->data->res_list->last = NULL;
s2->person->data->res_list->first = NULL;
s2->person->data->res_list->last = NULL;
Update -- You seem to be a little confused about linked list pointers and adding/removing nodes from multiple lists. If we look at a simple example:
List<Person*>* Person1 = new List<Person*>;
List<Person*>* Person2 = new List<Person*>;
List<Person*> List1;
List<Person*> List2;
List1.addLink(Person1);
List1.addLink(Person2); //Ok: List1 has two persons
List2.addLink(Person1); //Error: Person1 can't belong to both lists
Everything is fine until you try adding a node already in one list to another list. This will "mess up" your node next pointers in both lists.
Another confusion seems to be how to move all elements from one list to another. All you have to do is to set the head/tail of both lists, for example to move all nodes from List1 to List2 just do:
List2.first = List1.first;
List2.last = List1.last;
List1.first = NULL;
List1.last = NULL;
You don't need to touch the individual nodes in List1 as you aren't changing their pointer locations. If you want to copy all the nodes from List1 to List2 it is a bit different as you have to create new nodes.
If you are still having problems with your corrected code I would suggest reducing it to a small example that exhibits the problem and post another SO question.
I have the following loop in a class method:
vector<PuzzleImpl> PuzzleImpl::performMove()
{
//! Remove a single move from mMoves and store it in aMove.
MovesImpl aMove = mMoves.top();
mMoves.pop();
//! Cached local variables.
vector<size> soln = aMove.getSoln();
size RID = aMove.getRowID();
size CID = aMove.getColID();
size BID = aMove.getBlockID();
bool solvable = true;
//! Return Vector, will store all possible moves from aMove.
vector<PuzzleImpl> neighbours;
//! Build all Boards and update Moves Queue for a move from top of mMoves.
while (!soln.empty()) {
//! Store local copies to update without being destructive to original.
// Also reset updatedMoves and updatedBoard for next iteration.
fib_heap tempHeap = mMoves;
fib_heap updatedMoves;
Board<size> updatedBoard = mBoard;
//! Get a <value>, remove it form <soln>.
size value = soln.back();
soln.pop_back();
//! Update Board with the move.
updatedBoard.set(RID, CID, value);
//! Iterate through the mMoves queue and update for the removed move.
while (!tempHeap.empty()) {
//! Get an element, remove it from the heap.
MovesImpl temp = tempHeap.top();
tempHeap.pop();
//! If the temp object shares the same RID/CID/BID remove <value>.
if ((temp.getRowID() == RID) || (temp.getColID() == CID)
|| (temp.getBlockID() == BID)) {
temp.removeMove(value);
}
//! Check if we can solve the puzzle form this position. If you have
// a blank position left but there are have no moves from that
// position, a solution is unattainable. - HALT.
if (temp.getSolnSize() == 0) {
solvable = false;
break;
}
//! Add the Moves object to the updatedMoves Heap.
updatedMoves.push(temp);
}
//! If the puzzle is solvable from this position with the current move,
// generate new PuzzleImpl object using the Board and Moves Vec.
neighbours.push_back(PuzzleImpl(updatedBoard, updatedMoves, solvable));
}
//! Return the Vector containing all possible states from this move.
return neighbours;
}
The problem I have is in the line:
MovesImpl temp = tempHeap.top();
I get an access violation (Access violation reading location 0x0000000C.) stating that <src>'s memory can't be read and <this> is set to random values in memory. MovesImpl doesn't have any heap allocation, its stack based and I thus use the default assignment operator. I have specified the copy ctor.
Any ideas? Input greatly appreciated.
/Thanks!
Right I have two vectors. I want to empty the vector(list) and replace its contents with the contents of the other vector(templist) and clear templist when I've done that. Is this the right code?
list.clear();
list = templist;
templist.clear();
That is what the swap method is for:
list.swap(templist); // The contents are swapped
templist.clear(); // Clear the one you don't need anymore
Note that this is faster than list = templist because the contents are not copied.
All you need is this:
list = templist;
templist.clear();