I have an array of strings that I'm supposed to create a linked list with. The problem is I can only use arrays. Everything I've looked up says to use struct and nodes, and I'm not sure where to go from here. I know my code isn't right, I have the pointers pointing to one element of the array each, so they aren't really linked. If anyone can point me in the right direction that would be amazing
Here is what I have so far
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string names [4] = {"Dick", "Harry", "Sam", "Tom", " "};
string *nameptr[4];
for(int x = 0; x < 4; x++)
{
nameptr[x] = &names[x];
cout << *nameptr[x] << " is at position " << x << " and points to ";
cout << &nameptr[x] << endl;
}
return 0;
}
Here is a tutorial for linked lists in c++:
http://www.dreamincode.net/forums/topic/31357-c-linked-lists-custom-linked-lists-part-1/
You should search and have a go first in future, then when you ask people here will be able to better help you with your question. In fact read this as well:
http://mattgemmell.com/2008/12/08/what-have-you-tried/
Actually if using arrays, you only need a pointer to the first element, and you can access the rest of the array by pointer arithmetic.
However, if you want a real link list. then you could do something like this:
struct mydata{
std::string data;
struct mydata* next;
}
mydata names[4] = {{"Dick",NULL}, {"Harry",NULL}, {"Sam",NULL}, {"Tom",NULL}, {" ",NULL}};
//here you establish the link
names[0].next = &names[1];
names[1].next = &names[2];
names[2].next = &names[3];
names[3].next = &names[4];
//here is the pointer to the head;
mydata* nameptr = names;
while(nameptr)
{
cout << nameptr->data;
nameptr = nameptr->next;
}
What do you mean by "I can only use arrays"? You only know how to use arrays, or you are limited to only using arrays, or ??
You've looked up some stuff that's told you to use structs - have you tried doing this? It isn't in your code here.
Unrelated to your actual question, but you've declared an array of 4 strings (string names [4]), then you're trying to initialise that array with 5 items.
My advice is similar to what you've seen: use structures, and I'll add that you're going to need to use the heap as well (malloc in c, new in c++). The structure will need a link pointer to the next list element, and somewhere to store the data itself, in this case probably just a char pointer.
Related
I'm currently doing a programming exercise from a C++ book for beginners. The task reads as follows: "Write a function that reverses the characters in a text string by using two pointers. The only function parameter shall be a pointer to the string."
My issue is that I haven't been able to make the characters swap properly, see the output below. (And I also made the assumption that the function parameter doesn't count, hence why I'm technically using three pointers).
I am almost certain that the problem has to do with the for loop. I wrote this pseudocode:
Assign value of element number i in at_front to the 1st element in transfer_back.
Assign value of element number elem in at_back to element number i in at_front.
Assign value of the 1st element in transfer_back to element number elem in at_back.
Increment i, decrement elem. Repeat loop until !(i < elem)
I wasn't sure whether of not I was supposed to take the null terminator into account. I tried writing (elem - 1) but that messed up with the characters even more so I've currently left it as it is.
#include <iostream>
#include <string>
using namespace std;
void strrev(string *at_front) {
string *transfer_back = at_front, *at_back = transfer_back;
int elem = 0;
while(at_back->operator[](elem) != '\0') {
elem++;
}
for(int i = 0; i < elem; i++) {
transfer_back->operator[](0) = at_front->operator[](i);
at_front->operator[](i) = at_back->operator[](elem);
at_back->operator[](elem) = transfer_back->operator[](0);
elem--;
}
}
int main() {
string str = "ereh txet yna";
string *point_str = &str;
strrev(point_str);
cout << *point_str << endl;
return 0;
}
Expected output: "any text here"
Terminal window: "xany text her"
The fact that the 'x' has been assigned to the first element is something I haven't been able to grasp.
Here is the correct answer
void strrev(string *at_front) {
string *at_back = at_front;
char transfer_back;
int elem = 0;
while(at_back->operator[](elem) != '\0') {
elem++;
}
for(int i = 0; i <elem; i++) {
transfer_back = at_front->operator[](i);
at_front->operator[](i) = at_back->operator[](elem);
at_back->operator[](elem) = transfer_back;
elem--;
}
}
Let me explain why you have that error. string *transfer_back = at_front those two are pointed to the same reference, that is why when you change transfer_back->operator[](0) = at_front->operator[](i);this change will reflect in at_front string as well.
"Write a function that reverses the characters in a text string by using two pointers. The only function parameter shall be a pointer to the string."
This sounds to me like the question addresses C strings but not std::string.
Assuming my feeling is right, this could look like:
#include <iostream>
#include <string>
void strrev(char *at_front) {
char *at_back = at_front;
if (!*at_back) return; // early out in edge case
// move at_back to end (last char before 0-terminator)
while (at_back[1]) ++at_back;
// reverse by swapping contents of front and back
while (at_front < at_back) {
std::swap(*at_front++, *at_back--);
}
}
int main() {
char str[] = "ereh txet yna";
strrev(str);
std::cout << str << '\n';
return 0;
}
Output:
any text here
Live Demo on coliru
Note:
I stored the original string in a char str[].
If I had used char *str = "ereh txet yna"; I had assigned an address of a constant string to str. This feels very wrong as I want to modify the contents of str which must not be done on constants.
strrev():
The at_back[1] reads the next char after address in at_back. For a valid C string, this should be always possible as I excluded the empty string (consisting of 0-terminator only) before.
The swapping loop moves at_front as well as at_back. As the pointer is given as value, this has no "destructive" effect outside of strrev().
Concerning std::swap(*at_front++, *at_back--);:
The swapping combines access to pointer contents with pointer increment/decrement, using postfix-increment/-decrement. IMHO, one of the rare cases where the postfix operators are useful somehow.
Alternatively, I could have written:
std::swap(*at_front, *at_back); ++at_front; --at_back;
Please, note that std::string is a container class. A pointer to the container cannot be used to address its contained raw string directly. For this, std::string provides various access methods like e.g.
std::string::operator[]()
std::string::at()
std::string::data()
etc.
->Please see my edited question below the horizontal divider:
I was trying to return a string array from a function to another function. The code compiled successfully; however, it failed upon execution. I have included my code below:
string Occupant::LoadDataFunction()
{
string array[5] = {"hello", "you", "are", "a", "human"};
return array[5];
}
void Occupant::LoadData()
{
string loc_array[5];
loc_array[5] = Occupant::LoadDataFunction();
string park_array[5];
park_array[5] = Occupant::LoadDataFunction();
string lease_array[5];
lease_array[5] = Occupant::LoadDataFunction();
}
When I debugged the code, I found out that the problem was in the return statement of the function:
return array[5]
The debugger had the following output:
Signal = SIGSEGV (Segmentation Fault)
this = { Occupant * const | 0x61ff2f} 0x61ff2f
array = {std::_cxx11::basic_string< char, std::char_traits, std::allocator> [5]}
Can someone tell me what is wrong with my return statement, why it is causing a segmentation error? Thanks
** I know there are many other similar questions on the web, but none of them involved a segmentation fault in the return statement Therefore, I would appreciate it if this question is not marked as a duplicate. If you need any more information, just inform me in the comments box. Thanks for your help!
EDIT Thanks everyone, I didn't notice that glitch I just fixed it. I actually wanted to return the entire array, I did it with pointers this time. Here's my code:
string* Occupant::LoadDataFunction()
{
string* array = new string[5];
array[0] = "hello";
array[1] = "hello";
array[2] = "hello";
array[3] = "hello";
array[4] = "hello";
return array;
}
void Occupant::LoadData()
{
string **loc_array = new string*[5];
loc_array[5] = Occupant::LoadDataFunction();
string **park_array = new string*[5];
park_array[5] = Occupant::LoadDataFunction();
string **lease_array = new string*[5];
lease_array[5] = Occupant::LoadDataFunction();
for (int i = 0; i < 5; i++)
{
cout << &loc_array[i] << " : location" << endl;
cout << &park_array[i] << " : parking" << endl;
cout << &lease_array[i] << " : leased" << endl;
}
}
The problem now is that when I run the code, rather than printing hello fifteen times in total, it prints the memory address. Here's what I got:
0xf56d50 : location
0xf56df8 : parking
0xf56ea0 : leased
0xf56d54 : location
0xf56dfc : parking
0xf56ea4 : leased
0xf56d58 : location
0xf56e00 : parking
0xf56ea8 : leased
0xf56d5c : location
0xf56e04 : parking
0xf56eac : leased
0xf56d60 : location
0xf56e08 : parking
0xf56eb0 : leased
I expected a "Hello" word outputted wherever a memory address is outputted. Can anyone explain this now? Thanks for all your answers!
To return an array, use std::array, as a std::array is copyable and assignable, unlike a vanilla array.
#include <array>
#include <algorithm>
typedef std::array<std::string, 5> Array5Strings;
Array5Strings LoadDataFunction()
{
Array5Strings ret;
std::fill(ret.begin(), ret.end(), "hello");
return ret;
}
Also, I used std::fill to quickly set the items to "hello".
Live Example
If for some weird reason you can't use std::array, then the other alternative is to create a struct that contains an array of 5 strings, and return the struct. A struct is copyable, thus can be returned directly from a function.
#include <algorithm>
#include <string>
#include <algorithm>
#include <iostream>
struct Array5Strings
{
std::string sArray[5];
};
Array5Strings LoadDataFunction()
{
Array5Strings ret;
std::fill(std::begin(ret.sArray), std::end(ret.sArray), "hello");
return ret;
}
int main()
{
Array5Strings val = LoadDataFunction();
std::cout << val.sArray[0]; // prints the first value
}
Live Example
Regardless of which you choose, note that there are no pointers involved.
You are accessing the arrays using out of bounds index.
When you have an array declared as:
string loc_array[5];
the valid indices are 0 - 4.
Use of
loc_array[5] = Occupant::LoadDataFunction();
is cause for undefined behavior. I suspect you meant to use:
loc_array[4] = Occupant::LoadDataFunction();
Similarly, you need to use:
park_array[4] = Occupant::LoadDataFunction();
and
lease_array[4] = Occupant::LoadDataFunction();
You also need to change Occupant::LoadDataFunction.
string Occupant::LoadDataFunction()
{
string array[5] = {"hello", "you", "are", "a", "human"};
return array[4];
}
Update
The updated implementation of of Occupant::LoadDataFunction is better but there are still problems.
Each time the function gets called, you are allocating an array of strings. It's not clear whether that's the intention. If that's the intention, then the calling code has to take responsibility for deallocating that memory.
The calling code still suffers from out our bounds memory access. The line
string **loc_array = new string*[5];
allocates memory for 5 string*. The valid indices for loc_array is still 0 - 4. Hence,
loc_array[5] = Occupant::LoadDataFunction();
suffers from out of bounds memory access problem. It's not clear how you wish to use the return value of Occupant::LoadDataFunction. Hence, I am not able to suggest a way to solve the problem.
The lines
park_array[5] = Occupant::LoadDataFunction();
lease_array[5] = Occupant::LoadDataFunction();
suffer from the same problem.
Try returning array[4]. There is no array[5], since arrays start at index 0.
The range of an array of size N is from 0 to N-1. So the 5 is out of the range. And you may want to return an array as a result, but the array is constructed in the function LoadData, after the function is executed, the array is invalid. You may use dynamic allocation for your purpose or use a global variable.
When you use the dynamic allocation array, you can just use string* instead of string**, and you should release the allocated memory.
First off, if this problem seems incredibly easy to you, I want to in advance apologize but I am only a beginner.
I have been stuck now for about a week with this problem and it is getting ridiculous since it shouldn't be that hard, even for a complete beginner like me.
I am writing a program which reads a bunch of information regarding receipts from a text file, like name, sum, date etc. and then prints it out to the screen. Simple enough, right? Well I started with using static arrays in my two classes Transaction and TransactionsList and it was working fine, I was printing the contents of the file to the screen just fine one line after the other.
Now I need to do this using dynamic arrays.
Each line in the text file contains a date, type, name, sum, number of friends and name of those friends which should be read an stored as a Transaction class object inside the dynamic array trans. This is what I am having trouble understanding no matter how much theory and googling I do on the subject. Where should I use an overloaded assigment operator, where a copy constructor and how do I call them properly? I have read up on these concepts but I can't use them in my program still. These are questions just flying around in my head right now.
I have changed the arrays friends and trans to be declared as pointers which I understand is correct. I then want to allocate memory for the arrays with "new", but here I am starting to get unsure just where I allocate with new, inside the contructors of their classes or inside the functions where they are needed?
I realize vectors is the answer to alot of these problems but I should tell you that I have not gotten into vectors yet, so I am trying to solve this problem without vectors. I realize this may be be a bit backwards, but I should be able to build my dynamically allocated array of objects and print it out without vectors I think. I have heard they are more practical but for now I have to understand this assignment without the concept of vectors.
I have read up on difference between shallow copies and deep copies as well and I get the theory, but I just can't implement it somehow. (I am probably retarded I know).
This is what I have got so far:
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
class Transaction
{
private:
string date;
string type;
string name;
double sum;
int nr_friends;
string *friends;
public:
Transaction();
~Transaction();
Transaction &operator = ( const Transaction &t );
string get_name();
int get_no_friends();
double get_sum();
bool readOneTrans( istream &is );
void writeOneTrans( ostream &os );
};
class TransactionsList
{
private:
Transaction *trans;
int no_Trans;
public:
TransactionsList();
~TransactionsList();
void read( istream & is );
void print( ostream & os );
void add( Transaction & t );
};
int main()
{
ifstream inFile("test.txt");
Transaction t;
TransactionsList tl;
// t.readOneTrans(inFile); // reading just one line works fine (when uncommented)
// t.writeOneTrans(cout); // printing works too just fine
//tl.read(inFile); // here I want to read all contents of file
//tl.print(cout); // and here print out them to the screen
return 0;
}
Transaction::Transaction()
{
date = "000000";
type = "transp";
name = "default";
sum = 0.0;
nr_friends = 0;
friends = NULL;
}
Transaction::~Transaction()
{
delete [] friends;
}
Transaction &Transaction::operator = ( const Transaction &t )
{
if ( this != &t )
{
delete[] friends;
date = t.date;
type = t.type;
name = t.name;
sum = t.sum;
nr_friends = t.nr_friends;
friends = new string[nr_friends];
for ( int i = 0; i < nr_friends; i++ )
{
friends[i] = t.friends[i];
}
}
return *this;
}
string Transaction::get_name()
{
return name;
}
double Transaction::get_sum()
{
return sum;
}
int Transaction::get_no_friends()
{
return nr_friends;
}
bool Transaction::readOneTrans( istream &is )
{
is >> date >> type >> name >> sum >> nr_friends;
friends = new string[nr_friends];
for (int i = 0; i < nr_friends; i++)
{
is >> friends[i];
}
return is;
return !is.eof();
}
void Transaction::writeOneTrans( ostream &os )
{
os << left << setw(10) << date <<
setw(10) << type << setw(10) << name
<< setw(10) << sum << setw(10)
<< nr_friends;
for (int i = 0; i < nr_friends; i++)
{
os << left << setw(8) << friends[i];
}
os << endl;
}
TransactionsList::TransactionsList()
{
no_Trans = 1;
trans = new Transaction[no_Trans];
}
TransactionsList::~TransactionsList()
{
delete [] trans;
}
void TransactionsList::read( istream & is )
{
Transaction t;
while ( t.readOneTrans( is ))
{
add( t );
}
}
void TransactionsList::print( ostream & os )
{
Transaction t;
for (int i = 0; i < no_Trans; i++)
{
t = trans[i];
t.writeOneTrans( os );
}
if (os == cout)
{
os << "\nNumber of transactions: " << no_Trans << endl;
}
}
void TransactionsList::add( Transaction & t )
{
// each time I read a line from the file it is passed in as object t here
// here I want to add this object t to the dynamic array trans somehow
// and keep building the array with a new class object every time
// Probably by overloading assignment operator somehow but how?
trans[no_Trans] = t;
no_Trans++;
// i have no idea what to put here to make it work...
}
So as you can see, what I want to do is continually build up the dynamic array trans with different objects of the class Transaction, each instance representing a different line in the text file I am reading from so that I can print out all the lines in the file to the screen in the end.
The output lines should look like this:
011216 food John 300 2 Nathan Julia
To do this now dynamically, I realize I must copy the contents of object t that is passed in in the method "add" and add it to the array trans and somehow without losing the data of the earlier t:s which are representing the previous text lines. This was easy for me to do while the arrays where static ones, as I just assigned the next element in the array trans to be equal to the current object t (inside the add function). This is how my add function looked with static arrays:
void TransactionsList::add( Transaction & t )
{
trans[no_Trans] = t;
no_Trans++;
}
Obviously this doesn't work when you are working with dynamically allocated memory. I read some theory on this and I understand one cannot change the size of the array while it is running so the array actually has to be deleted and then allocated as a larger array and copy over the old contents using a deep copy, which doesn't just copy the memory address for the dynamic array but makes a new array with the olds content.
As you can see, I have read alot of theory but don't really understand it...
Can anyone help? I would be immensely thankful as I have not learned anything in a week and this is really killing me right now. I need to make progress now!
Some hints about the container:
Don't use using namespace std; (why?)
An unsigned integral size in c++ is usually represented as std::size_t from <cstddef>.
Get familiar with rule of three / rule of three/four/five.
A quite useful idiom that is usually applied to such classes is: 'Resource Acquisition Is Initialization (RAII)'.
Bottom line:
When managing resources we usually need to have
a destructor
a copy constructor
a move constructor
a copy assignment operator
a move assignment operator
Resource aquisition should only happen in the constructor.
Functions such as add should not perform seperate resource acquisition but create a temporary of appropriate size and swap/move contents.
The issue of constructing a dynamically-allocated array is completely separate from the issue of constructing the objects themselves.
class TransactionList {
Transaction *trans;
size_t trans_size;
size_t no_Trans;
public:
TransactionList(size_t initial_size)
: trans(new Transaction[initial_size]),
trans_size(initial_size),
no_Trans(0)
{
}
~TransactionList()
{
delete[] trans;
}
// ...
};
That's it. There's nothing different about your existing add() method. It still works exactly the same way, because of the fact that an array is really just a pointer to the first element in the array, which is still the case here.
But you do need to figure out what to do when no_Trans reaches the actual allocated trans_size. That's going to be your homework assignment.
What you probably want to do, though, is to change this to an array of Transaction * objects, and also dynamically allocate each Transaction when it's added to the array. That will require additional work.
(This answer requires no extra knowledge, and needs only a little bit change of your code)
Things get weird in the constructor:
no_Trans = 1;
trans = new Transaction[no_Trans];
People usually leave some space for future elements to add:
max_Trans = 100;
no_Trans = 0;
trans = new Transaction[max_Trans];
And in add()
if (no_Trans >= max_Trans) { // no more space?
// make a new array that is as twice big as the old one
max_Trans = 2 * max_Trans;
Transaction new_trans = new Transaction[max_Trans];
// copy elements to the new array
for (int i = 0; i < no_Trans; i++)
new_trans[i] = trans[i];
// delete the old one and start to use the new one
delete[] trans;
trans = new_trans;
}
trans[no_Trans] = t;
no_Trans++;
Of course max_Trans can also be 1, and make it grow as 1, 2, 3, 4... But that requires new on each add operation, which is inefficient.
I reacently learned about map structures and I am trying to use one, but can't seem to solve one problem.
I have tried the code below:
map<string, valuePair> translator;
The class valuePair is just a combination of 2 objects (string and a number).
Im assigning values to the map
translator[currentWord] = valuePair(stateNo, "state");
Where currentWord is a variable string, stateNo is an int.
Now later I want to get back the valuePair number value from the map, but can;t seem to be able to do it.
Heres a screenshot of my watch window trying to access the variable x.
http://i.imgur.com/m3MOgi2.png
These are all the ways I managed to find online to return the value, yet none of them seem to work. As you can see the key "a" is in the map. What am I doing wrong?
[EDIT] Thanks guys, I used the tips you gave in comments and found out, that actually it works the way I expected - translator["a"].x prints the values I need. I have nothing to mark as "Correct answer" though, and I'm not sure what to do with this thread now :/
As Jonathan Henson posted in the comments, you would be better off posting your code than your debugger output. Ideally you want a minimal example that reproduces the error you are having.
Based on the debugger output, I'm wondering if you have a scope issue -- you are trying to access the map data outside of the scope where you have it defined. Without seeing the source code though, there is no way to know.
Here is a working example that does precisely what you are trying to do. The only modification is I have used a struct for valuePair, and c++ 11 initializer lists. This won't affect the map access code, but you might need to turn on c++ 11 support to compile it.
As a first step, look check it out in your debugger and see if you get the same difficulty. If so, your problem is the debugger or debugger setup, not your code.
If the debugger works for the sample code (posted below), gradually transform my code into your code (making minimal changes, building, and see if it still works). This is a very useful approach to learning the fine points of a language.
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct valuePair
{
int num;
string str;
};
int main()
{
map<string, valuePair> translator;
translator["a"] = {0,"bla"};
translator["b"] = {1, "alb"};
translator["c"] = {2, "lab"};
valuePair res = translator["c"];
cout << "c:" << res.num << "," << res.str << "\n";
res = translator.at("b");
cout << "b:" << res.num << "," << res.str << "\n";
res = translator.find("a")->second;
cout << "a:" << res.num << "," << res.str << "\n";
return 0;
}
If you have an std::map<K,V> m; you can add elements and change values by using m[k] = v;. However the operator[] is an operation which always creates a key/value pair, if the key you are looking for is not contained in the map. Thus it is not allowed when you have a const reference or pointer, e.g. const std::map<K,V>&.
With a std::map you always have to consider the case that the key you are looking for is actually not contained in the map!
To look for the value stored under a given key you have to use std::map::find (link).
Example:
std::map<std::string,valuePair>::const_iterator it = translator.find(currentWord);
if(it != translator.end()) {
// the map contains an element with this key
const valuePair& value = it->second; // this is the value
}
else {
// the map *does not* contain an element with this key
}
As mentioned in the comments std::map::at (link) may be an alternative for C++11. But then you have to take care of the possible exception which is thrown when you use a key which does not exist in the map.
this works for me
#include <map>
#include <sstream>
#include <string>
int main()
{
std::map<std::wstring, double> items;
items[L"0"] = 0.123;
items[L"1"] = 1.234;
items[L"2"] = 2.234;
items[L"3"] = 3.345;
items[L"4"] = 4.567;
for (int i = 0; i < 5; i++)
{
std::wstringstream oss;
oss << i;
std::wstring key = oss.str();
double value = items[key];
}
return 0;
}
I've googled a lot now, and I still can't find any solution to this... The thing is, that I'm trying to make a program that stores different points in a coordinate system, and displays them on the screen (it will later turn into a type of graph, but I'm not quite there yet). But unfortunately, I've had some issues with this...
I've decided to store all the the points in addresses after each other, of type string, like this:
string p;
string * pointer = &p;
p = "5, 3";
*(&p+1) = "6, 4";
*(&p+2) = "7, 5";
cout << *pointer << *(pointer+1) << *(pointer+2);
Or this:
string p;
string * pointer = &p;
p = "5, 3";
*(pointer+1) = "6, 4";
*(pointer+2) = "7, 5";
cout << *pointer << *(pointer+1) << *(pointer+2);
But whenever I get to line 4 or 5, I get an error on this row in the memcpy assembly:
mov [edi],al ;U - write second byte to destination
So apparently this doesn't work...
I'm starting to suspect that it has something to do with the fact that the pointer points to an address of type string, which consists of char arrays, but I'm not sure why nor how... If it now is like this, why would it even be possible to use string pointers?
Regardless, any solution/explaination is appreciated, really. I haven't really used pointers that much in the past, so excuse me if I'm missing something obvious. But as said, I've tried searching for this, and I can't find anything.
Your first code will not even compile.
Your second code attempts to store values into std::string objects presumably located after p in memory. But there are no std::string objects after p in memory. Any attempts to "store" anything into those non-existing objects leads to undefined behavior.
If you declared your p as an array
string p[3];
string * pointer = p;
*pointer = "5, 3"; // same as `p[0] = "5, 3"`
*(pointer+1) = "6, 4"; // same as `p[1] = "6, 4"`
*(pointer+2) = "7, 5"; // same as `p[2] = "7, 5"`
cout << *pointer << *(pointer+1) << *(pointer+2);
then the second version of the code would safely store the strings into consecutive elements of that array.
But what you have now just doesn't make sense. And it is not immediately clear what you are trying to do.
Don't use pointers, they are difficult, and you have some serious (and strange) misunderstanding about how they work. Just use a vector.
#include <vector>
struct Point
{
Point(int xx, int yy) : x(xx), y(yy) {}
int x;
int y;
};
std::vector<Point> p;
p.push_back(Point(5,3));
p.push_back(Point(6,4));
p.push_back(Point(7,5));
I've defined a simple Point class because that also seems sensible if you are writing a program about points. But if you really want to store your points as strings then replace std::vector<Point> with std::vector<std::string>.
Why don't you simply do this:
string p1 = "5, 3";
string p2 = "6, 4";
string p3 = "7, 5";
cout << p1 << p2 << p3;
If you have more points, you could use a vector like that:
vector<string> points;
points.push_back("5, 3");
points.push_back("6, 4");
points.push_back("7, 5");
cout << points[0] << points[1] << points[2];
By the way, why do you want to store coordinates in a string instead of a float array for example ?
First of all, you take the address of a std::string object and you increment it - std::string is not (w)char[]. It does store its data contiguously but it also stores some meta-data in an implementation defined manner. So you're overwriting something that just happens to be in the memory - and you're overwriting it with something that mismatches its type, therefore it won't even compile.
When manipulating std::strings, you can use the operator[] that will give you access to the actual data of the string.
That said, I am pretty sure you do NOT want to store random pointers to string. Ideally, make a class Point<T> with T x, y; data members to store the coordinates.