I'm trying to learn about vectors in C++, but just trying to declare one throws a runtime error in NetBeans.
Error: Run failed (exit value -1, 073, 741, 511, total time 51 ms)
PS: The code works perfectly in Eclipse.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// create a vector to store int
vector<int> vec;
int i;
// display the original size of vec
cout << "vector size = " << vec.size() << endl;
// push 5 values into the vector
for (i = 0; i < 5; i++) {
vec.push_back(i);
}
// display extended size of vec
cout << "extended vector size = " << vec.size() << endl;
// access 5 values from the vector
for (i = 0; i < 5; i++) {
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while (v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}
return 0;
}
I have tested on my system (latest GCC and NB dev build) and it works without any problem. The desired output is shown. It also runs fine from command line.
Therefore I assume it's more a configuration or system related problem. But without any further informations it's impossible to find the root cause.
More information please:
What OS / Environment are you using?
What Compiler (and versions) do you have?
What version of Netbeans do you use?
Do other project's work?
Here's some first aid you can try:
Create a new C++ Project (C++ Application). It already includes a blank main() function. Run this and check if there's still an error
Create a simple .cpp file and build it from command line (don't involve any IDE). Does it work this way?
Build and your source file without IDE. From Commandline: g++ <your filename>.cpp
Review your compiler settings (Tools -> Options -> C/C++ at Build Tools). Especially use the Version button and check if everything is right.
Windows only: Make sure you have the correct make executable selected in the compiler settings
Have a look at the IDE's log (View -> IDE Log). Are there any problems mentioned?
Run in Debug without any breakpoint. This is going to stop the execution on any runtime error.
Related
When I am programming in C++ and Visual Studio 2019 throws an error, it shows in which line it was encountered. But when coding with C++ when error is thrown, it does not show in which line exactly it appears. So it makes hard to debug and fix my program. Maybe there are settings that I need to adjust?
C++ error (it point to some 1501 line of installation files that weren't created by me):
vector<int> myVector(2);
cout << myVector[4] << endl;
Errors in both programs in these examples are of a same category: vector (in C++).
Without providing more code and looking at the minimal c++ code you provided:
vector<int> myVector(2);
cout << myVector[4] << endl;
It looks like you have too many elements in myVector in the second line. You will have UB because the [] operator does not allocated more elements. You only declared 2 elements.
Now, when you send your vector to cout you are saying you have 4 which is false.
That is why you are getting the error: "Expression: vector subscript out of range".
You only have two indices 0 and 1, if you define a vector with 2 elements.
Now if you were trying to see the size of your vector you use the .size() function which returns the number of elements in the vector.
vector<int> myVector(2);
cout << myVector.size() << endl;
You could even do something like this with a for loop:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> myVector(2);
std::cout << myVector.size() << std::endl;
for (int i = 0; i < 10; i++)
myVector.push_back(i);
std::cout << myVector.size() << '\n';
return 0;
}
MatrixXd p(10,10);
// set values of p
// for loop prints out all values of p
for (int i = 0; i < 100; i++)
std::cout << p(i/10,i%10) << std::endl;
const IOFormat CleanFmt(4,0,", ","\n","[","]");
std::cout << p.format(CleanFmt);
// fails before running any code with error 1 (cxx = 20)
// fails before running any code with error 127 (cxx = 14/11)
Having trouble debugging this, as it is failing outright. My OS setup is Cygwin in Windows. Perhaps it is failing since windows does not support FIFO-Qs?
Or is something wrong going on here?
I have spent 2 days chasing an issue involving C++ container, std::list, and C-Style structs. Is the following undefined behavior (Note the type for the std::list parameter)?
#include <list>
#include <iostream>
using std::cout;
using std::endl;
struct Point_Struct
{
int x;
int y;
};
typedef struct Point_Struct Point;
int main()
{
std::list<Point> line;
Point p;
p.x = 3;
p.y = 10;
line.push_back(p);
cout << "Size of container: " << line.size() << "\n";
// Here's the issue:
line.pop_back();
// The size should be zero.
cout << "Size of container after pop_back(): " << line.size() << "\n";
return 0;
}
I ran this on Visual Studio 2017 and I get an exception error, 0xC0000005, (memory access) on the call to pop_back.
The exception is also thrown on any method that changes the ordering of the items in the list, such as assignment and sort.
If I change the type of line to std::list<Point_Struct>, there are no exceptions thrown.
Note: The issue was found in a larger program. The code above illustrates the root cause of the issue: std::list<typedef struct> vs. std::list<struct>
Note: The exception is thrown in VS2017 debug mode but not in release mode.
Sorry, but multiple questions follow:
Is there anything in standard C++ (11 or later) declaring undefined
behavior for using a typedef instead of a struct as the template
parameter for std::list?
Would this be a Visual Studio bug?
I haven't tried on G++ or other compilers.
Edit 1: VS2017 version info
Microsoft Visual Studio Professional 2017
Version 15.9.14
Installed product: Visual C++ 2017 - 00369-60000-00001-AA071
Compilation Info
Configuration: Debug
Platform: Win32
Warning Level: Level3 (/W3)
Optimization: Disabled (/Od)
Enable C++ Exception: Yes (/EHsc)
Basic Runtime Checks: Both (/RTC1)
Disable Language Extensions: No
Conformance mode: No
Platform
Platform: Windows 7
I compiled and ran your code with g++ 11 in Eclipse (Ubuntu 18) and it worked perfectly,
Output:
Size of container: 1
Size of container after pop_back(): 0
Have you tried/is it possible to swap typedef for using? This might fix it:
#include <list>
#include <iostream>
using std::cout;
using std::endl;
struct Point_Struct
{
int x;
int y;
};
using Point = Point_Struct;
int main()
{
std::list<Point> line;
Point p;
p.x = 3;
p.y = 10;
line.push_back(p);
cout << "Size of container: " << line.size() << "\n";
// Here's the issue:
line.pop_back();
// The size should be zero.
cout << "Size of container after pop_back(): " << line.size() << "\n";
return 0;
}
I have a two-dimensional array that I want to print to the output of visual studio to see the result each time I modify that, I tried using std::cout and it does not work, if I use CCLOG the function will automatically write a newline each time it's called that and it's not a two-dimensional array pretty solution, I also tried CClog not sure what's the difference with CCLOG but this time it even give a compiling error :(
like I want the output be:
1,2,4,4,5
5,5,4,3,0
4,4,4,4,7
6,6,6,6,6
Here is what I tried:
void HelloWorld::PrintBrickArray() {
CCLOG("will print brick array");
std::cout << "===Begin of Array ====" << std::endl;
for (int i = 0; i < MATRIX_Y; i++) {
for (int j = 0; j < MATRIX_X; j++) {
//CCLog("%d", this->brickArray[i][j]);
std::cout << this->brickArray[i][j] << ' ';
}
std::cout << std::endl;
}
std::cout << "*****END OF Array *****" << std::endl;
std::cout.flush();
}
How to do that with coco2dx?
CCLOG or cocos2d::log uses the Visual Studio's Debug windows, which is different to write to console where std::cout works.
Therefore, there are two ways to get rid of your problem: writing to console using std::cout or writing to output windows using different methods than CCLOG
First choice, you have to change your project type from Win32 Application Project to Win32 Console Project. This is kind of going around with Visual Studio stuffs, and in most cases, your project is created automatically via cocos2d's console. You can see this post. I'm not recommend this way IMO.
Second choice, use your own code to write to output which discussed here.
There is another way that you can use std::string and std::ostringstream to "print" your variables to buffer, and then just print your string to output windows via CCLOG
CCLOG is a little bit wrapping the code to make it convenience where we log resources checking, errors, file processing, etc which usually occur when run time. If not in those cases, you should probably set break points to view what the values are instead.
Edited: Since you chose the second approach, I would recommend using std::ostringstream than sprintf, and using CCLog instead of OutputDebugString (because you just print it out and independent OS, no need extra arguments)
Here is an example code:
#include <vector>
#include <sstream> // for ostringstream
#include <Windows.h> // for OutputDebugStringA
using namespace std;
int main(void)
{
// Assuming that you have this 2d array
vector< vector<int> > arr2d;
arr2d.push_back({ 2,2,1,4 });
arr2d.push_back({ 2,4,1,5 });
arr2d.push_back({ 2,4,7,2 });
arr2d.push_back({ 3,2,0,1 });
ostringstream buffer;
for (int i = 0; i < arr2d.size(); i++)
{
for (int j = 0; j < arr2d[i].size(); j++)
{
buffer << arr2d[i][j] << '\t';
}
buffer << endl;
}
// Assuming that you use OutputDebugString for windows-only
//OutputDebugStringA(buffer.str().c_str());
// I recommend this
cocos2d::log(buffer.str().c_str());
return 0;
}
Now, buffer works nearly the same as cout, it just "print" to buffer instead, then you can get one using str(). But cocos2d::log use C-style string, so c_str() will get rid of the problem
See more about std::ostringstream here
I am writing code for a project in my computer science course and I am testing my algorithm to see if it works and how fast it is. I know that the algorithm works because when I launch the program in Visual Studio 2013, I get the correct output. But, when I launch the .exe from the Visual Studio projects folder in the command line or from windows explorer, the first two cout statements are displayed correctly, but the cout statements during the for loop are not displayed at all. Again this only happens when I launch the .exe outside of Visual Studio. It isn't a big problem, but I wonder what's going on here. Thanks.
Here is int main() (The first 2 couts work and the others don't):
int main() {
// declare input stream for reading dctnryWords.txt
ifstream inFile;
// create a pointer to memory in the heap
// where each word in the dictionary will be stored
string* words = new string[DICTIONARY_SIZE];
// create a vector of forward_lists to hold
// adjacent words for each word in the dictionary
vector< list<string> > adjacents(DICTIONARY_SIZE);
// open dctnryWords.txt
inFile.open("dctnryWords.txt");
// load words into RAM
cout << "Loading words into RAM took: "
<< time_call([&] { copyDictionary(inFile, words); })
<< "ms\n";
cout << "Finding adjacent words took: "
<< time_call([&] { searchAdjacents(words, adjacents); })
<< "ms\n";
for (int i = 0; i < DICTIONARY_SIZE; i++) {
if (adjacents[i].size() >= 25) {
cout << words[i] << "(" << adjacents[i].size()
<< "): ";
for (list<string>::const_iterator j = adjacents[i].cbegin(); j != adjacents[i].cend(); j++) {
cout << *j << " ";
}
cout << endl << endl;
}
}
return 0;
}
I'll bet a nickel your program isn't finding "dctnryWords.txt" when you launch it elsewhere... because it's going to look in the current directory, which is likely different when you run it outside of VS.