Tag Archives: c++

Solved: could not find the task ‘G + + build active file, leetcode algorithm ACM compilation and debugging

Project scenario:

Environment: Ubuntu 20.04

Tool: vscode

Because leetcode can’t debug the code (for members), it’s necessary to configure the local environment to run the code.

Leetcode’s code is to help you configure all the environments. You only need to write the core code, but you need to write all the code yourself during the interview. It’s ACM mode (Baidu ACM). At this time, if you don’t often write all the code, it’s easy to be confused (this is what happened when I was deeply convinced in the online interview)

So it’s necessary to configure the local environment and write the whole process of algorithm implementation, including the compilation process and principle of cpp file, and the debug process can make you more familiar with the code running process.

Reference for compiling environment configuration: https://code.visualstudio.com/docs/cpp/config-linux

No Baidu, no Baidu! Look at the official statement is always the best!!! If you don’t understand English, you can right-click to translate the web page directly.

My task.json configuration: it is automatically generated. The configuration of the computer and the environment is different, so this file may be different.

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: g++ Generate activity files",
			"command": "/usr/bin/g++",
			"args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}"],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			},
			"detail": "Compilers: /usr/bin/g++"
		}
	]
}

My launch.json:

{
    "version": "0.2.0",
    "configurations": [
      {
        "name": "g++ build and debug active file",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}/${fileBasenameNoExtension}",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": false,
        "MIMode": "gdb",
        "setupCommands": [
          {
            "description": "Enable pretty-printing for gdb",
            "text": "-enable-pretty-printing",
            "ignoreFailures": true
          }
        ],
        "preLaunchTask": "g++ build active file",
        "miDebuggerPath": "/usr/bin/gdb"
      }
    ]
  }

Problem Description.
I encountered the following situation when configuring task.json for compiling C++ and debugging configuration file launch.json.


Cause Analysis.
Code encountered problems suggest direct google …
Reference: https://stackoverflow.com/questions/59106732/visual-studio-code-debugger-error-could-not-find-the-task-gcc-build-active-f

In your task.json file, no task is labeled as ‘gcc build active file’ which is required as a preLaunchTask in launch.json file.

So you can either change the label of task or change the content of preLaunchTask to make them match.

The answer is clear: task.json file this configuration

"label": "C/C++: g++ Generate activity files",

This configuration must be the same as launch. JSON

"preLaunchTask": "g++ build active file",

Solution:

Configure task.json as follows:

"label": "C/C++: g++ Generate activity files",

To be amended as follows:

"label": "g++ build active file",

—————————The following can be ignored———————————-

As long as the two values are the same. You can be like this: (yes, that’s what I changed it to.)

"label": "g++ build active file  hahaha",

OpenCV(-206:Bad flag (parameter or structure field)) Unrecognized or unsupported array type [How to Solve]

This problem occurred when I ran C + + opencv code. I realized that the mask format I entered was incorrect, not the. PNG or. JPG problem I wrote. The source of the problem may be that CV2. Imread() is loading an empty matrix. Instead of delving into this problem, I will check your input image and mask name and format again. I think this error is a sign that the image cannot be loaded correctly. You need to check your code imread read read problem, whether the file name is correct and whether there is a problem with the file input path. Finally, I changed the way the file path was read

My modification: change the input path in the program parameters to:

The above is my solution to this problem, the correct operation of the modified code.

libxx.so: undefined reference, vector.reserve(n) [How to Solve]

background: Trying to avoid reallocation using the STL: std::vector.reserve(n).
declared static std::vector<int> sample_num in class AngleCal, and want to do it in AngleCal::AngleCal() sample_num.reserve(300) (assumming 300 is the size or, alternatively an upper bound on the size)


However, when compiling this AngleCal.cpp into libanglecal.so, the compiler gives the following error.
[build] /usr/bin/ld: ../lib/libanglecal.so: undefined reference to `hitcrt::AngleCal::if_first_detection’
[build] /usr/bin/ld: ../lib/libanglecal.so: undefined reference to `hitcrt::AngleCal::sample_num’
[build] /usr/bin/ld: ../lib/libanglecal.so: undefined reference to `hitcrt::AngleCal::i’
Solution: A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can’t put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

#include <iostream>
 
using namespace std;

class Box {
   public:
      static int objectCount;
      
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         
         // Increase every time object is created
         objectCount++;
      }
      double Volume() {
         return length * breadth * height;
      }
      
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void) {
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects.
   cout << "Total objects: " << Box::objectCount << endl;

   return 0;
}

The running results are as follows

Constructor called.
Constructor called.
Total objects: 2

Static decorated class members must be initialized outside the class before they can be manipulated.

above.

Vs error unresolved external symbol_ Main, the symbol in the function “int”__ cdecl invoke_ main

Cause analysis

There are many reasons for this problem. The first and most common one is that there are multiple CPP files in your project, which contain multiple main functions
the second is that your code is copied from QQ or other ways (such as Notepad). In this case, the newline character may change. According to the explanation of the online boss, the newline character has many codes. If the format is wrong, there will be problems. At this time, you will be prompted to convert the source file to DOS or UNIX format, If there is a warning, it means that you are in this situation. You need to find the advanced save option in the file menu of vs (the advanced version needs to be called out in the settings, but not Baidu search), and then select window (CR LF), which means that the new line character supported by the window system indicates that the problem is solved ~
the third is that your project is created incorrectly, If your compiler’s preprocessor is not right, you can copy the code directly to the new correct project, or open the project settings and modify your preprocessor. You can search for it.

C++ Error: terminating with uncaught exception of type std::out_of_range: vector Abort trap: 6

Toss about for a long time, finally clear the specific reason!
According to the exception prompt, vector is out of bounds, but it has not been located to which vector variable for a long time.
Write the class printf before and after the interrupt position, find the interrupted function, and print inside the function, only to find that the function doesn’t go in at all. It’s strange how you can’t go back in, no other thread, no other place to cause a crash. At this point, I should have thought to check the input of the function earlier. If the input is not correct, the function cannot enter. However, I have never encountered the situation that the input causes the function to not enter, so I did not think to check the input.
The input is a vector type, and the error is due to a problem with the access method.
Vector has a variety of access methods, which can be accessed directly in the way of array, such as VEC variable, VEC [0], or at(), vec.AT (0). There are differences between the two approaches. If veC happens to be empty, accessing the 0th element as an array will not be considered wrong, but the second access using the at method will result in the above error!!

Off line data storage and upload scheme

For reprint, please indicate the source: http://blog.csdn.net/itas109  

 

QQ technology exchange group: 129518033

 

Solution download address:

http://download.csdn.net/detail/itas109/9859688

GitHub related projects:

https://github.com/itas109/OfflineDataStorge

 

introduction

 

Nowadays, with the wide spread of network, the development of all walks of life have a great dependence on the network. Instantaneous network disconnection may cause huge losses to some industries, such as banking, finance and other industries with large amount of data. Network disconnection or network transmission failure may cause some immediate key data loss, In order to ensure the reliability of real-time data generation, sending and storage in some industries, especially the security of real-time data uploaded by clients, it is very important to use a secure offline data storage and automatic retransmission mechanism

Off line data storage technology

SQLite is a lightweight database, is to comply with the acid relational database management system, it is contained in a relatively small C library. It’s a public domain project founded by D. Richard HIPP. Its design goal is embedded, and it has been used in many embedded products. It occupies very low resources. In embedded devices, it may only need a few hundred K of memory. It can support Windows/Linux/Unix and other mainstream operating systems, and can be combined with many programming languages, such as TCL, C #, PHP, Java, etc., as well as ODBC interface. It is also faster than MySQL and PostgreSQL, two open source world-famous database management systems.

Unlike the common client server paradigm, the SQLite engine is not an independent process with which a program communicates, but a major part of it by connecting to the program. So the main communication protocol is the direct API call in the programming language. This has a positive effect on total consumption, delay time and overall simplicity. The entire database (definition, table, index and data itself) is stored in a single file on the host.

Cppsqlite encapsulates the API of SQLite once, which makes it more convenient for developers to use SQLite.

Automatic retransmission

The timer is used to check SQLite database on time during programming. If there is any data, it will be sent back and uploaded automatically to avoid the loss of data after transmission failure

Data upload solution

The existing problems: the data type is not unified when uploading, the data is scattered, the corresponding processing information is given for different data, and the data specification is stored when using the database

Solution: the design of the database only needs to give the key fields. The data submitted at one time is packaged into a type and stored as a data field (i.e. JSON data). The data and corresponding methods are stored by JSON. After sending successfully, the data is parsed according to JSON, so that different data can be stored in the other end of the database according to the corresponding type

The design of the database is as follows

Field:

id: INT
Data: TEXT
UpdateTime:DATETIME

 

 

JSON format:

 

{
    "businesses": [
        {
            "logicFunction":"firstFunction",
            "parms": [
                {
                    "parm":"1"
                }
            ]
        },
        {
            "logicFunction":"secondFunction ",
            "parms": [
                             {
                    "parm": "2"
                },
                {
                    "parm": "3"
                }
            ]
        }
    ]
}

 

 

Businesses: business array. The default business order is the storage order of the array

Parms: parameter array

ParM: the specific parameter value must be consistent with the parameter of the function corresponding to logicfunction

Logicfunction: logical function, used to determine which function to execute after data analysis, and its parameter is the value of parms array

For example, in this example, the first function is executed first, and then the second function is executed. If both functions succeed at the same time, it means success. In this way, the problem of business-related data retransmission is solved.

 

 

Think the article is helpful to you, you can scan the QR code to donate to the blogger, thank you!

 

For reprint, please indicate the source: http://blog.csdn.net/itas109  

QQ technology exchange group: 129518033

 

 

 

How to use C + + function pointer array

2015-11-24

1、 Origin

Under what circumstances did you come up with an array of function pointers?Because there are a series of sequential functions in a program recently written, and the forms of these functions are basically the same, it is necessary to judge the execution result of each step, whether the execution is successful or not. If the execution is successful, the next function will continue to be executed. If the execution fails, the terminal will execute and exit.

Because there are many functions to be executed in turn, there are five. To write code according to the conventional way of thinking is to judge the result of each step by if-else, and decide the content of the next step according to the result. At present, there are only five functions to be executed. If there are more similar functions to be executed in sequence, this function will be very long, not easy to read, and the code will not be beautiful.

Considering that the parameter list and return value of the current function are basically the same, we consider whether we can traverse the function pointer array, store the function pointer in the array and traverse the array, so as to execute the function pointed to by the corresponding pointer in turn, judge the results one by one, and do the corresponding processing. In this way, the result processing part can adopt a unified way, which is very convenient to judge, the code is also very simple and clear, and it is easy to read.

So online query related information, to understand the use of function pointer array. Through data query, the use of C + + function pointer array can be divided into two categories, one is the use of global function pointer array (the same as C language), the other is the use of C + + member function pointer array. Now the two cases are sorted out respectively.

2、 The use of global function pointer array in C

(1) Requirements

1. The parameter list and return value type of a series of functions to be called should be identical;

2. It is required to put the function pointer to be called into the function pointer array (if the function must have sequential execution, then the storage order of the function pointer should be consistent with the calling order);

3. When calling, take out the function pointer to be executed from the array and execute the corresponding function.

(2) Code case

Reference from: http://blog.csdn.net/feitianxuxue/article/details/7300291

 

#include <iostream> 

using namespace std; 

 

void function0(int); 

void function1(int); 

void function2(int); 

 

int _ tmain(int argc, _ TCHAR* argv[]) 

Void (* f [3]) (int) = {function0, function1, function2};// save the three function pointers in the array F

      intchoice;

      cout<< “Enter a number between 0 and 2,3 to end: “;

      cin>> choice;

//handle user selection

      while((choice >= 0) && (choice <3))

      {

//call a function in the array f

(* f [choice]) (choice);// F [choice] select the pointer whose position is choice in the array.

//the pointer is dereferenced to call the function, and choice is passed as an argument to the function.

             cout<< “Enter a number between 0 and 2,3 to end: “;

             cin>> choice;

      }

      cout<< “Program execution completed.” << endl;

      system(“pause”);

      return0;

}

 

void function0(int a)

{

      cout<< “You entered” << a << ” so function0 wascalled\n\n”; 

}

 

void function1(int b)

{

      cout<< “You entered” << b << ” so function1 wascalled\n\n”;

}

 

void function2(int c)

{

      cout<< “You entered” << c << ” so function2 wascalled\n\n”;

}

3、 The use of pointer array of member function in C + + class

(1) Requirements

When using the pointer array of member function in C + + class, it is different from that of C. The requirements are as follows:

1. It is required that the parameter list and return value type of the member function put into the function pointer array are completely consistent;

2. Define a function pointer array, and specify the length of the array (equal to the number of member functions to be stored), and assign the member function pointer to the corresponding array variable during initialization (if the function must have sequential execution, the storage order of the function pointer should be consistent with the calling order);

3. When calling, take out the function pointer to be executed from the array and execute the corresponding function. When calling, use “& gt; *” or “. *” to point to array elements, otherwise an error will be reported during compilation.

(2) Code case

Reference from: http://www.cppblog.com/dragon/archive/2010/12/02/135250.html

 

/*

* small program for testing pointer array of member function

* key points of the code have been marked in red

 */

#include <iostream>

using namespace std;

 

class Test

{

public:

   Test();

   ~Test();

 

private:

   void add5(){ res+=5;}

   void add6(){ res+=6;}

//this 2 is very important. If it is not written in VC, an error will be reported, but it is not reported in QT, but an error will be reported during the deconstruction!

    void (Test::*add[2])();

public:

   void DoAddAction();

   void Display();

private:

   int res;

};

 

Test::Test()

{

//pay attention to the writing here

    add[0]=&Test::add5;

    add[1]=&Test::add6;

   res=0;

}

 

Test::~Test()

{

 

}

 

void Test::DoAddAction()

{

    for (int i=0;i<2;i++)

    {

//using class member function pointer must have a call of “& gt; *” or “. *”

        (this->*add[i])();

    }

}

 

void Test::Display()

{

   cout<<“The res is:”<<res<<endl;

}

 

int main()

{

   Test * test=new Test();

   test->DoAddAction();

   test->Display();

   delete test;

   return 0;

}

4、 Summary

The above methods illustrate the method of using function pointer array in C and C + + classes. It is obvious that using function pointer array can call functions more conveniently, make the code concise and beautiful, and provide a level of code quality.

In the future program development process, we encounter similar problems. When we can use the function pointer array, we can try to only use the function pointer array to make the development easier and more fun.

Vs generated an error: “error LNK 1168: unable to open xxxxxx.exe Write to

When writing C + + code with VS, you often encounter this situation when you finish writing the code generation project: “error LNK 1168: unable to open xxxxxx.exe Write.

 

There are three solutions (the first two are temporary but not permanent, and the third is radical)

1. Do nothing, wait for a moment, about a few minutes, you can successfully generate.

2. Delete the. EXE file generated in the previous debug folder, and it will be generated successfully.

3. The most fundamental way: open the control panel – & gt; management tools – & gt; Services – & gt; to enable the application experience service.