473,385 Members | 1,449 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

vector 'push_back' problem

Al
What is the problem with this code? It always crashes at the
'push_back'. I found that thanks to debugging. Any Ideas?
Other question: what is a faster way to convert a string to an integer?
Is there a built-in function to do that?
Here's the code:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int stringToInt(string text)
{
int integer=0, temp=1;
for (int i=text.size()-1, j=1;i>=0;i--, j++)
{
switch (text[i]) {
case 49:
integer += temp; break;
case 50:
integer += 2 * temp; break;
case 51:
integer += 3 * temp; break;
case 52:
integer += 4 * temp; break;
case 53:
integer += 5 * temp; break;
case 54:
integer += 6 * temp; break;
case 55:
integer += 7 * temp; break;
case 56:
integer += 8 * temp; break;
case 57:
integer += 9 * temp; break;
default: break;
}
temp *= 10;
}
return integer;
}

template<class T>
void print(vector<T> v)
{
for (int i=0; i<v.size(); i++)
cout << i <<" : "<<v[i]<<endl;
}

int main()
{
ifstream is("D:/dataa.txt");
vector<vector<int> > theMat;
string data = "";
char c;
int number;
for (int i=0;;i++)
{
while (is.get(c)) {
if (c == '\t') theMat[i].push_back(stringToInt(data));
//here is the problem: the program crashes
else if (c == '\n') break;
else data += c;
}
}
print(theMat[0]);
/*string test = "132435";
cout <<stringToInt(test); */

system("pause");
return 0;
}

Dec 25 '05 #1
3 3192
On 25 Dec 2005 12:20:26 -0800, "Al" <al************@gmail.com> wrote:
What is the problem with this code? It always crashes at the
'push_back'. I found that thanks to debugging. Any Ideas?
Other question: what is a faster way to convert a string to an integer?
Is there a built-in function to do that?
Yes. You want either std::stringstream or the CRT strtod() function.
The latter is better for sanity-checking of input. The former is
easier to use.
Here's the code:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int stringToInt(string text)
Since you do not change "text", it should be passed by const
reference. Otherwise, you are copying it unnecessarily.
{
int integer=0, temp=1;
It's considered bad style by many people to declare more than one
variable on the same line.
for (int i=text.size()-1, j=1;i>=0;i--, j++)
What happens when text.size() == 0?
What happens when text.size() > 10?
What happens when text holds non-digit characters?
What happens when text is negative?
Where is j used in the loop?
{
switch (text[i]) {
This is not necessarily portable code because you are making
assumptions about the internal representation of the particular
character encoding used. Better to use something like this:

case '1':
integer += temp; break;
case '2':
integer += 2 * temp; break;
// etc.

Note the single quotes used.
case 49:
integer += temp; break;
case 50:
integer += 2 * temp; break;
case 51:
integer += 3 * temp; break;
case 52:
integer += 4 * temp; break;
case 53:
integer += 5 * temp; break;
case 54:
integer += 6 * temp; break;
case 55:
integer += 7 * temp; break;
case 56:
integer += 8 * temp; break;
case 57:
integer += 9 * temp; break;
default: break;
}
temp *= 10;
}
return integer;
}

template<class T>
void print(vector<T> v)
{
for (int i=0; i<v.size(); i++)
size() returns unsigned. It's a very bad mistake to compare signed
with unsigned values, even if your compiler lets you do it. Turn up
your warning level so that you at least get a warning about it here.
cout << i <<" : "<<v[i]<<endl;
}

int main()
{
ifstream is("D:/dataa.txt");
vector<vector<int> > theMat;
string data = "";
char c;
int number;
for (int i=0;;i++)
{
while (is.get(c)) {
The std::getline() function is much better than reading a file
character-for-character.
if (c == '\t') theMat[i].push_back(stringToInt(data));
//here is the problem: the program crashes
theMat is a vector of vectors. It was never initialized. Therefore, it
has no elements, yet you use element 0, therefore it crashes.
else if (c == '\n') break;
else data += c;
}
}
print(theMat[0]);
/*string test = "132435";
cout <<stringToInt(test); */

system("pause");
return 0;
}


--
Bob Hairgrove
No**********@Home.com
Dec 25 '05 #2

Al wrote in message
<11**********************@o13g2000cwo.googlegroups .com>...
What is the problem with this code? It always crashes at the
'push_back'. I found that thanks to debugging. Any Ideas?
// You need to initialize the vector with a size:
// here's one way:
size_t rows(480);
size_t cols(640);
vector<vector<int> > theMat( rows, cols);

size_t row(4);
size_t col(6);
theMat.at(row).at(col) = 43; // set 5th row, 7th col to 43
// unless you are positive the index[s] are not out-of-range
// you should use the at() to access the vector[s].

// another way to do it
vector<vector<int> > theMat;
for(size_t i(0); /* you need a way out */ ; ++i){
std::vector<int> tmp;
theMat.push_back( tmp ); // each pass add another row.
while (is.get(c)) {
if (c == '\t') theMat.at( i ).push_back( FromString<int>(data) );
// ...... fill in data ....
} //while()
if( not is ) break;
} // for()

Other question: what is a faster way to convert a string to an integer?
Is there a built-in function to do that?


There are stringstream ToString() and FromString() templates/methods in some
FAQs.

#include <sstream>
// --- string to any number ---
template<typename T> T FromString(std::string const &str){
std::istringstream is(str); T tmp; is >> tmp; return tmp;
} //FromString()
// -- use it like this --
std::string Str("54321");
int num = FromString<int>(Str);
double num2 = FromString<double>(Str);

Heed Mr. Hairgrove's suggestions.

The comp.lang.c++ FAQ is available at http://www.parashift.com/c++-faq-lite/

[corrections always welcome]
--
Bob R
POVrookie
Dec 26 '05 #3
"BobR" <Re***********@worldnet.att.net> wrote in message
news:Uk*********************@bgtnsc04-news.ops.worldnet.att.net...
Other question: what is a faster way to convert a string to an integer?
Is there a built-in function to do that?


There are stringstream ToString() and FromString() templates/methods in
some
FAQs.

#include <sstream>
// --- string to any number ---
template<typename T> T FromString(std::string const &str){
std::istringstream is(str); T tmp; is >> tmp; return tmp;
} //FromString()
// -- use it like this --
std::string Str("54321");
int num = FromString<int>(Str);
double num2 = FromString<double>(Str);


Here is the version I use:

#include <sstream>
template<typename T, typename F > T StrmConvert( F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >> to;
return to;
}

The advantage of this version is that you can convert from/to std::string
without problems using your same syntax.

int num = 12345;
std::string str("67890");

std::string str2 = StrmConvert<std::string>( num );
int num2 = StrmConvert<int>( str );

You don't have to specify the type to convert from, the template figures
that out itself (somehow I'm not really positive on the mechanics). You
just have to specify what you are converting to.
Dec 26 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: David Jones | last post by:
Hi I have a list of values stored in a vector e.g. std::vector<int> x; x = 1; x = 4; x = 2; x = 4;
4
by: Tran Tuan Anh | last post by:
Dear all, I am new in C++, and now get confused about a lot of things. I wrote this simple code to test the vector. class Temp { public: int x; }; int main() { vector<Temp> v;
2
by: Dave | last post by:
I'm crossposting this to both comp.lang.c++ and gnu.gcc because I'm not sure if this is correct behavior or not, and I'm using the gcc STL and compiler. When calling vector<int>::push_back(0),...
4
by: Venn Syii | last post by:
I've searched all the forums but cannot find an answer to this question. I do the following: vector<MyClass*> myClassList; Later in the program I try to add to myClassList with a...
5
by: Billy Patton | last post by:
I have a polygon loaded into a vector. I need to remove redundant points. Here is an example line segment that shows redundant points a---------b--------c--------d Both b and c are not...
6
by: Lorn | last post by:
Hopefully someone can help me out with this problem I'm having with 2d vectors. My vector initialization looks like this: struct Object { double d1; double d2; int i1; }; ...
6
by: Jia | last post by:
Hi all, I have a class foo which has a static vector of pointers of type base class, and a static function to set this vector. #include <iostream> #include <vector> using namespace std;...
4
by: Josefo | last post by:
Hello, is someone so kind to tell me why I am getting the following errors ? vector_static_function.c:20: error: expected constructor, destructor, or type conversion before '.' token...
8
by: Bryan | last post by:
Hello all. I'm fairly new to c++. I've written several programs using std::vectors, and they've always worked just fine. Until today. The following is a snippet of my code (sorry, can't...
3
by: Ramon F Herrera | last post by:
Newbie alert: I come from C programming, so I still have that frame of mind, but I am trying to "Think in C++". In C this problem would be solved using unions. Hello: Please consider the...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.