Changing one element in a two-dimensional vector changes all elements?Concatenating two std::vectorsHow to find out if an item is present in a std::vector?How do I erase an element from std::vector<> by index?Test if a vector contains a given elementWhat is the easiest way to initialize a std::vector with hardcoded elements?Appending a vector to a vectorWhy does changing 0.1f to 0 slow down performance by 10x?How to print out the contents of a vector?Get all the combinations of a vector of vector. into a new VectorIterating values into a vector while reading in a file using getline

How do I, as a DM, handle a party that decides to set up an ambush in a dungeon?

My large rocket is still flipping over

Can my 2 children, aged 10 and 12, who are US citizens, travel to the USA on expired American passports?

Can full drive backup be used instead of MSSQL database backup?

Clarification of algebra in moment generating functions

Endgame puzzle: How to avoid stalemate and win?

In "Avengers: Endgame", what does this name refer to?

All of my Firefox add-ons been disabled suddenly, how can I re-enable them?

Dirichlet series with a single zero

What makes an isotope stable?

weird pluperfect subjunctive in Eutropius

Why is my arithmetic with a long long int behaving this way?

Understanding ties

Dihedral group D4 composition with custom labels

Madam I m Adam..please don’t get mad..you will no longer be prime

All superlinear runtime algorithms are asymptotically equivalent to convex function?

Which US defense organization would respond to an invasion like this?

Would a small hole in a Faraday cage drastically reduce its effectiveness at blocking interference?

Is any special diet an effective treatment of autism?

Why did the Apollo 13 crew extend the LM landing gear?

Can I hide the part of long lines that exceeds the visual line?

Why did WWI include Japan?

How to remap repeating commands i.e. <number><command>?

Is it normal for gliders not to have attitude indicators?



Changing one element in a two-dimensional vector changes all elements?


Concatenating two std::vectorsHow to find out if an item is present in a std::vector?How do I erase an element from std::vector<> by index?Test if a vector contains a given elementWhat is the easiest way to initialize a std::vector with hardcoded elements?Appending a vector to a vectorWhy does changing 0.1f to 0 slow down performance by 10x?How to print out the contents of a vector?Get all the combinations of a vector of vector. into a new VectorIterating values into a vector while reading in a file using getline






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm coding a checkered board game where the board is a two-dimensional vector that holds a Square object, and the Square holds a Piece. Using a nested for-loop, I'm initializing a new Square object in each slot in the 8x8 vector - but when I add a Piece to one Square, it's adding a Piece to every single Square. I think that, somehow, each slot in the vector is only pointing to one Square, even though I'm initializing a new Square every time.



I've tried this with a two-dimensional vector of Square objects as well as with a vector of Square pointers. Currently I'm using the vector of pointers: vector<vector<Square*>> _board;



 // initializing an empty board
_board = ,,,,,,,;

// adding a new Square to each of the 8x8 slots
string colorAlternator = WHITE;
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
_board[i].push_back(new Square(colorAlternator, make_tuple(i,j)));
if (colorAlternator == WHITE)
colorAlternator = BLACK;
else
colorAlternator = WHITE;




// placing a piece
/* placePiece() is a function of Square
* (p2Pieces.at(0) is a piece being pulled from elsewhere)
*/
_board[0][1]->placePiece(*p2Pieces.at(0));


In another function called view(), it prints out a visualization of the board (excuse my inelegant implementation, it will be fixed with a for-loop shortly!):



for (int i = 7; i >= 0; i--)
"
<< board[i][3]->displayToken() << "


This should be printing every Square as being blank except for the one I placed the Piece in - but it's printing each Square out as containing the Piece I just added.



Any ideas what's causing each slot in the vector to be linking to the same Square? (Or is that even what's happening?)



update: here is the implementation for placePiece(), displayToken(), and supporting method containsPiece() in class Square:



Piece* _piece;

void Square::placePiece(Piece &piece)
_piece = &piece;


bool Square::containsPiece()
return _piece != nullptr;


string Square::displayToken()
string displayStr = " ";

if (containsPiece())
displayStr = _piece->getToken();


return displayStr;










share|improve this question
























  • // initializing an empty board -- Why not simply _board.resize(8);? Also, it isn't a good idea to name your variables with leading underscores.

    – PaulMcKenzie
    Mar 23 at 2:50












  • @PaulMcKenzie Ah, thanks - I'm new to C++ and didn't know that was a method I could call. (As for the underscores, that's thanks to the style guides I have to work under.)

    – Kimberly H
    Mar 23 at 2:57











  • Show the implementation of placePiece and displayToken. Better still, prepare a Minimal, Complete, and Verifiable example. The problem is somewhere in the code you haven't shown. Does Square` have a static data member, by any chance?

    – Igor Tandetnik
    Mar 23 at 3:28












  • @IgorTandetnik I've added those implementations; and no, Square doesn't have any static methods or data members.

    – Kimberly H
    Mar 23 at 3:44











  • Where and how is _piece initialized? What, if anything, ensures that it's equal to nullptr in most squares?

    – Igor Tandetnik
    Mar 23 at 4:35

















0















I'm coding a checkered board game where the board is a two-dimensional vector that holds a Square object, and the Square holds a Piece. Using a nested for-loop, I'm initializing a new Square object in each slot in the 8x8 vector - but when I add a Piece to one Square, it's adding a Piece to every single Square. I think that, somehow, each slot in the vector is only pointing to one Square, even though I'm initializing a new Square every time.



I've tried this with a two-dimensional vector of Square objects as well as with a vector of Square pointers. Currently I'm using the vector of pointers: vector<vector<Square*>> _board;



 // initializing an empty board
_board = ,,,,,,,;

// adding a new Square to each of the 8x8 slots
string colorAlternator = WHITE;
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
_board[i].push_back(new Square(colorAlternator, make_tuple(i,j)));
if (colorAlternator == WHITE)
colorAlternator = BLACK;
else
colorAlternator = WHITE;




// placing a piece
/* placePiece() is a function of Square
* (p2Pieces.at(0) is a piece being pulled from elsewhere)
*/
_board[0][1]->placePiece(*p2Pieces.at(0));


In another function called view(), it prints out a visualization of the board (excuse my inelegant implementation, it will be fixed with a for-loop shortly!):



for (int i = 7; i >= 0; i--)
"
<< board[i][3]->displayToken() << "


This should be printing every Square as being blank except for the one I placed the Piece in - but it's printing each Square out as containing the Piece I just added.



Any ideas what's causing each slot in the vector to be linking to the same Square? (Or is that even what's happening?)



update: here is the implementation for placePiece(), displayToken(), and supporting method containsPiece() in class Square:



Piece* _piece;

void Square::placePiece(Piece &piece)
_piece = &piece;


bool Square::containsPiece()
return _piece != nullptr;


string Square::displayToken()
string displayStr = " ";

if (containsPiece())
displayStr = _piece->getToken();


return displayStr;










share|improve this question
























  • // initializing an empty board -- Why not simply _board.resize(8);? Also, it isn't a good idea to name your variables with leading underscores.

    – PaulMcKenzie
    Mar 23 at 2:50












  • @PaulMcKenzie Ah, thanks - I'm new to C++ and didn't know that was a method I could call. (As for the underscores, that's thanks to the style guides I have to work under.)

    – Kimberly H
    Mar 23 at 2:57











  • Show the implementation of placePiece and displayToken. Better still, prepare a Minimal, Complete, and Verifiable example. The problem is somewhere in the code you haven't shown. Does Square` have a static data member, by any chance?

    – Igor Tandetnik
    Mar 23 at 3:28












  • @IgorTandetnik I've added those implementations; and no, Square doesn't have any static methods or data members.

    – Kimberly H
    Mar 23 at 3:44











  • Where and how is _piece initialized? What, if anything, ensures that it's equal to nullptr in most squares?

    – Igor Tandetnik
    Mar 23 at 4:35













0












0








0








I'm coding a checkered board game where the board is a two-dimensional vector that holds a Square object, and the Square holds a Piece. Using a nested for-loop, I'm initializing a new Square object in each slot in the 8x8 vector - but when I add a Piece to one Square, it's adding a Piece to every single Square. I think that, somehow, each slot in the vector is only pointing to one Square, even though I'm initializing a new Square every time.



I've tried this with a two-dimensional vector of Square objects as well as with a vector of Square pointers. Currently I'm using the vector of pointers: vector<vector<Square*>> _board;



 // initializing an empty board
_board = ,,,,,,,;

// adding a new Square to each of the 8x8 slots
string colorAlternator = WHITE;
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
_board[i].push_back(new Square(colorAlternator, make_tuple(i,j)));
if (colorAlternator == WHITE)
colorAlternator = BLACK;
else
colorAlternator = WHITE;




// placing a piece
/* placePiece() is a function of Square
* (p2Pieces.at(0) is a piece being pulled from elsewhere)
*/
_board[0][1]->placePiece(*p2Pieces.at(0));


In another function called view(), it prints out a visualization of the board (excuse my inelegant implementation, it will be fixed with a for-loop shortly!):



for (int i = 7; i >= 0; i--)
"
<< board[i][3]->displayToken() << "


This should be printing every Square as being blank except for the one I placed the Piece in - but it's printing each Square out as containing the Piece I just added.



Any ideas what's causing each slot in the vector to be linking to the same Square? (Or is that even what's happening?)



update: here is the implementation for placePiece(), displayToken(), and supporting method containsPiece() in class Square:



Piece* _piece;

void Square::placePiece(Piece &piece)
_piece = &piece;


bool Square::containsPiece()
return _piece != nullptr;


string Square::displayToken()
string displayStr = " ";

if (containsPiece())
displayStr = _piece->getToken();


return displayStr;










share|improve this question
















I'm coding a checkered board game where the board is a two-dimensional vector that holds a Square object, and the Square holds a Piece. Using a nested for-loop, I'm initializing a new Square object in each slot in the 8x8 vector - but when I add a Piece to one Square, it's adding a Piece to every single Square. I think that, somehow, each slot in the vector is only pointing to one Square, even though I'm initializing a new Square every time.



I've tried this with a two-dimensional vector of Square objects as well as with a vector of Square pointers. Currently I'm using the vector of pointers: vector<vector<Square*>> _board;



 // initializing an empty board
_board = ,,,,,,,;

// adding a new Square to each of the 8x8 slots
string colorAlternator = WHITE;
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
_board[i].push_back(new Square(colorAlternator, make_tuple(i,j)));
if (colorAlternator == WHITE)
colorAlternator = BLACK;
else
colorAlternator = WHITE;




// placing a piece
/* placePiece() is a function of Square
* (p2Pieces.at(0) is a piece being pulled from elsewhere)
*/
_board[0][1]->placePiece(*p2Pieces.at(0));


In another function called view(), it prints out a visualization of the board (excuse my inelegant implementation, it will be fixed with a for-loop shortly!):



for (int i = 7; i >= 0; i--)
"
<< board[i][3]->displayToken() << "


This should be printing every Square as being blank except for the one I placed the Piece in - but it's printing each Square out as containing the Piece I just added.



Any ideas what's causing each slot in the vector to be linking to the same Square? (Or is that even what's happening?)



update: here is the implementation for placePiece(), displayToken(), and supporting method containsPiece() in class Square:



Piece* _piece;

void Square::placePiece(Piece &piece)
_piece = &piece;


bool Square::containsPiece()
return _piece != nullptr;


string Square::displayToken()
string displayStr = " ";

if (containsPiece())
displayStr = _piece->getToken();


return displayStr;







c++ c++11 vector stdvector






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 3:43







Kimberly H

















asked Mar 23 at 2:46









Kimberly HKimberly H

814




814












  • // initializing an empty board -- Why not simply _board.resize(8);? Also, it isn't a good idea to name your variables with leading underscores.

    – PaulMcKenzie
    Mar 23 at 2:50












  • @PaulMcKenzie Ah, thanks - I'm new to C++ and didn't know that was a method I could call. (As for the underscores, that's thanks to the style guides I have to work under.)

    – Kimberly H
    Mar 23 at 2:57











  • Show the implementation of placePiece and displayToken. Better still, prepare a Minimal, Complete, and Verifiable example. The problem is somewhere in the code you haven't shown. Does Square` have a static data member, by any chance?

    – Igor Tandetnik
    Mar 23 at 3:28












  • @IgorTandetnik I've added those implementations; and no, Square doesn't have any static methods or data members.

    – Kimberly H
    Mar 23 at 3:44











  • Where and how is _piece initialized? What, if anything, ensures that it's equal to nullptr in most squares?

    – Igor Tandetnik
    Mar 23 at 4:35

















  • // initializing an empty board -- Why not simply _board.resize(8);? Also, it isn't a good idea to name your variables with leading underscores.

    – PaulMcKenzie
    Mar 23 at 2:50












  • @PaulMcKenzie Ah, thanks - I'm new to C++ and didn't know that was a method I could call. (As for the underscores, that's thanks to the style guides I have to work under.)

    – Kimberly H
    Mar 23 at 2:57











  • Show the implementation of placePiece and displayToken. Better still, prepare a Minimal, Complete, and Verifiable example. The problem is somewhere in the code you haven't shown. Does Square` have a static data member, by any chance?

    – Igor Tandetnik
    Mar 23 at 3:28












  • @IgorTandetnik I've added those implementations; and no, Square doesn't have any static methods or data members.

    – Kimberly H
    Mar 23 at 3:44











  • Where and how is _piece initialized? What, if anything, ensures that it's equal to nullptr in most squares?

    – Igor Tandetnik
    Mar 23 at 4:35
















// initializing an empty board -- Why not simply _board.resize(8);? Also, it isn't a good idea to name your variables with leading underscores.

– PaulMcKenzie
Mar 23 at 2:50






// initializing an empty board -- Why not simply _board.resize(8);? Also, it isn't a good idea to name your variables with leading underscores.

– PaulMcKenzie
Mar 23 at 2:50














@PaulMcKenzie Ah, thanks - I'm new to C++ and didn't know that was a method I could call. (As for the underscores, that's thanks to the style guides I have to work under.)

– Kimberly H
Mar 23 at 2:57





@PaulMcKenzie Ah, thanks - I'm new to C++ and didn't know that was a method I could call. (As for the underscores, that's thanks to the style guides I have to work under.)

– Kimberly H
Mar 23 at 2:57













Show the implementation of placePiece and displayToken. Better still, prepare a Minimal, Complete, and Verifiable example. The problem is somewhere in the code you haven't shown. Does Square` have a static data member, by any chance?

– Igor Tandetnik
Mar 23 at 3:28






Show the implementation of placePiece and displayToken. Better still, prepare a Minimal, Complete, and Verifiable example. The problem is somewhere in the code you haven't shown. Does Square` have a static data member, by any chance?

– Igor Tandetnik
Mar 23 at 3:28














@IgorTandetnik I've added those implementations; and no, Square doesn't have any static methods or data members.

– Kimberly H
Mar 23 at 3:44





@IgorTandetnik I've added those implementations; and no, Square doesn't have any static methods or data members.

– Kimberly H
Mar 23 at 3:44













Where and how is _piece initialized? What, if anything, ensures that it's equal to nullptr in most squares?

– Igor Tandetnik
Mar 23 at 4:35





Where and how is _piece initialized? What, if anything, ensures that it's equal to nullptr in most squares?

– Igor Tandetnik
Mar 23 at 4:35












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310132%2fchanging-one-element-in-a-two-dimensional-vector-changes-all-elements%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310132%2fchanging-one-element-in-a-two-dimensional-vector-changes-all-elements%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript