Click here to Skip to main content
12,625,698 members (37,875 online)
Rate this:
Please Sign up or sign in to vote.
See more: C++

I have a 2D vector and want only the last column to change each time. I want the previous row to be copied over (with 1 less element).

Basically if i have an 2D vector visualised as:

1 2 3 4
. . . . <---- I want this line to be 2 3 4 (?) where the ? is a value inputted by other means.

So if I had it working it would be like this:

1 2 3 4
2 3 4 20
3 4 20 5
4 20 5 6

so user inputted last value (done)
How do I copy the previous row's values (except the first value) over? I've tried copy ( ) and MyVector.insert( ) ... but the only way I can get working is using a for loop which takes several lines. Can I not use a function like insert when it involves the same vector being copied? Many thanks.
P.S. The first line is inputted before I try the insert.
Posted 7-Dec-12 5:06am
André Kraak 7-Dec-12 10:24am
You might want to consider using something different like a list, which should make what you want to do easier.
lostandconfused1234 7-Dec-12 10:27am
Yes, well I have it working using a while loop so:
while(n < NumColumns-1) *inserts the data*,
I'm just trying to optimise my code into the shortest number of lines possible. Somewhat interesting as to why I can't do:
while (file != eof) {
MyVector.insert ( MyVector[i], Myvector[i][1], MyVector[i].end() );
lostandconfused1234 7-Dec-12 10:28am
forgot my manners - thank you though :D
Quirkafleeg 7-Dec-12 11:49am
A deque should be the preferred option to a list.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

An std::list could pop'n'push at its both sides :) :
typedef std::list<int> listYours;
typedef std::auto_ptr<listYours> ptrYours;
void ProduceShiftedListByValue(const ptrYours& listExist, ptrYours& listNew, int iValue)
  listNew.reset(listExist.get() ?
                new listYours(*listExist.get()) : // assumed std::list has a copy constructor :)
  if (listNew.get()) {
    if (listNew->size()) {
typedef std::list<ptrYours> 2dYours;
// or: typedef std::list<listyours&> 2dYours;
// or: typedef std::list<listyours> 2dYours;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.161205.3 | Last Updated 7 Dec 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100