Using namespace std python

[Solved]-Comparing #include and using namespace std in C++ with import in Python-C++

#include is «copy-paste this file». For example, you can #include a file into itself, and get this ridiculousness. You can also have a snippet of code in a file and #include it everywhere you want.

//forloop.txt for(int i=0;i //prime.txt 2147483647 //main.cpp #include using std::cout; using std::string; int main() < int prime = #include "prime.txt" ; int arr[10]; #define ARRAY arr #define SIZE 10 #define VALUE prime #include "forloop.txt" #undef VALUE #undef SIZE #undef ARRAY for(int i=10;i-- >0;) < cout> 

The using directive is not strictly needed. C++ has an idea of «namespaces» that prevents, for example, your max function to be considered different from the math function in cmath . It looks something like this:

namespace std < int max(int i, int j)< if (i//some variable declaration and initialization ostream cout(MAKE_BUFFER(stdout)); //std::ostream, if used outside > int max = 5; int main() < std::cout<

using namespace std; practically means «If you can’t find a name globally, try sticking std:: in front and see if that’s a name.» People say it’s bad practice to say using namespace std partly because if you #include «F.h» , and F.h has using namespace std , then your code also uses namespace std (due to copy-paste #include ).

Python is not a compiled language. When you say import X , you’re giving a command to the interpreter to do something (run some code and make some name). #include is more like telling the compiler what to do to continue compiling at this point.

import in Python kind of means, «attach the names in this module». So import blah as x means, «Every variable (including functions) in blah can be accessed as x.THING «. It also calls the module’s initialization stuff, which makes sense, because the variables need to be initialized before you can use them.

Java is also a compiled language. In Java, the import statement doesn’t play with files, it plays with classes. Every piece of code in Java has to belong to a class.

But unlike the other two languages, import is not strictly necessary. import is actually closer to C++’s using . import simply adds names for classes you can already use, except only to the current class.

Here’s some code using imports.

import java.util.Scanner; public class Example < public static void main(String blargs[])< Scanner cin = new Scanner(System.in); System.out.println("Type in your name and press Enter: "); System.out.println("Hello "+cin.next()); >> 

Here’s the same program, using no imports.

Here’s the same program, using all long names ( import java.lang.*; is implicit in every Java source file).

Here’s the same program, using all the imports.

import java.util.Scanner; import static java.util.System.out; import static java.util.System.in; public class Example < public static void main(String blargs[])< Scanner cin = new Scanner(in); out.println("Type in your name and press Enter: "); out.println("Hello "+cin.next()); >> 
  • Comparing #include and using namespace std in C++ with import in Python
  • include and using namespace in C++
  • using namespace std and library
  • c++ — using std namespace and dependancies
  • Where do I put the .so file from Boost.Python so I can import it as a module, and how do I use it with both Python 2 and 3
  • Is there a way to reference cout without using namespace std or prefixing with std.
  • C++: Questions about using namespace std and cout
  • Compile C++ with embedded Python using CMake Import error
  • I would like to remove using namespace std from this code, but am unsure what all needs to be prefixed with std::
  • C++ using for std and boost namespace best practice
  • A simple comparison with left and right stops working namespace std is not used
  • C++ long double precision difference with and without using namespace std;
  • using namespace std and Template Classes
  • Using std Namespace
  • CMake with include and source paths — basic setup
  • using OpenCV and SVM with images
  • Difference in behavior while using dynamic_cast with reference and pointers
  • C++ namespace and include
  • Given a 1 TB data set on disk with around 1 KB per data record, how can I find duplicates using 512 MB RAM and infinite disk space?
  • Using string literals without using namespace std
  • Sending a C++ array to Python and back (Extending C++ with Numpy)
  • Secure this invaluable documentation on using C/C++ with GSSAPI and SASL
  • What is the difference between using a struct with two fields and a pair?
  • Calling Python script from C++ and using its output
  • Using global namespace qualifiers with pointer to data members
  • C++: using namespace and #include
  • How to compile OpenGL with a python C++ extension using distutils on Mac OSX?
  • Generating a SHA256 hash with Crypto++, using a string as input and output?
  • With Eclipse: How to add include paths and libraries for all your C/C++ project
  • Speed difference between using int and unsigned int when mixed with doubles

More Query from same tag

  • How do I implement a simple relational database?
  • Visual Studio projects with multiple folders
  • How to properly initialize a C++11 std::seed_seq
  • godbolt fails to link when including windows.h on MSVC?
  • WSARecv() and multiple buffers
  • SPOJ Problem KPRIMES2
  • Modifying reference member from const member function in C++
  • changing const values at develop-time without recompiling everything
  • What can be done to prevent misleading assigment to returned value?
  • CRC-CCITT Implementation
  • Strategy for wrapping C++ objects with another language — memory management
  • Creating a Makefile to build swigged modules
  • Visual Studio set command arguments
  • in c++ main function is the entry point to program how i can change it to an other function?
  • Where should I include ?
  • Check at compile time if a template argument type is set or multiset, and element type of the container is arithmetic
  • binding a function object which is itself created by std::bind makes trouble
  • Another issue with specialised pure virtual template function (undefined reference)
  • Why does virtual inheritance need to be specified in the middle of a diamond hierarchy?
  • Defining member function of explicitly specialized class outside of the class definition
  • Fill the Grid with three colors A and B and C
  • setuptools: build shared library from C++ code, then build Cython wrapper linked to shared library
  • Debug Assertion Failed
  • Boost Program Options: Description too wide for terminal
  • Does accessing raw memory through a cast to an int violate strict aliasing?
  • Manually installing pyodbc on Windows with firewall
  • Objects with arguments and array
  • Making plot in Qt
  • Are newly allocated elements of std::vector initialized to 0?
  • Reusing a QMenu within multiple Qmenu

Источник

Python Programming/Extending with C++

There are different ways to extend Python with C and C++ code:

  • In plain C, using Python.h
  • Using Swig
  • Using Boost.Python, optionally with Py++ preprocessing
  • Using pybind11
  • Using Cython.

This page describes Boost.Python. Before the emergence of Cython, it was the most comfortable way of writing C++ extension modules.

Boost.Python comes bundled with the Boost C++ Libraries. To install it on an Ubuntu system, you might need to run the following commands

$ sudo apt-get install libboost-python-dev $ sudo apt-get install python-dev

Contents

A Hello World Example [ edit | edit source ]

The C++ source code (hellomodule.cpp) [ edit | edit source ]

#include using namespace std; void say_hello(const char* name)  cout  <"Hello "  <name  <"!\n"; > #include  #include  using namespace boost::python; BOOST_PYTHON_MODULE(hello)  def("say_hello", say_hello); > 

setup.py [ edit | edit source ]

#!/usr/bin/env python from distutils.core import setup from distutils.extension import Extension setup(name="PackageName", ext_modules=[ Extension("hello", ["hellomodule.cpp"], libraries = ["boost_python"]) ]) 

Now we can build our module with

The module `hello.so` will end up in e.g `build/lib.linux-i686-2.4`.

Using the extension module [ edit | edit source ]

Change to the subdirectory where the file `hello.so` resides. In an interactive python session you can use the module as follows.

>>> import hello >>> hello.say_hello("World") Hello World!

An example with CGAL [ edit | edit source ]

Some, but not all, functions of the CGAL library already have Python bindings. Here an example is provided for a case without such a binding and how it might be implemented. The example is taken from the CGAL Documentation.

// test.cpp using namespace std; /* PYTHON */ #include  #include  #include  namespace python = boost::python; /* CGAL */ #include  #include  #include  typedef CGAL::Cartesiandouble> K; typedef CGAL::Range_tree_map_traits_2K, char> Traits; typedef CGAL::Range_tree_2Traits> Range_tree_2_type; typedef Traits::Key Key; typedef Traits::Interval Interval; Range_tree_2_type *Range_tree_2 = new Range_tree_2_type; void create_tree()  typedef Traits::Key Key; typedef Traits::Interval Interval; std::vectorKey> InputList, OutputList; InputList.push_back(Key(K::Point_2(8,5.1), 'a')); InputList.push_back(Key(K::Point_2(1.0,1.1), 'b')); InputList.push_back(Key(K::Point_2(3,2.1), 'c')); Range_tree_2->make_tree(InputList.begin(),InputList.end()); Interval win(Interval(K::Point_2(1,2.1),K::Point_2(8.1,8.2))); std::cout  <"\n Window Query:\n"; Range_tree_2->window_query(win, std::back_inserter(OutputList)); std::vectorKey>::iterator current=OutputList.begin(); while(current!=OutputList.end()) std::cout  <" "  <(*current).first.x()  <","  <(*current).first.y()  <":"  <(*current).second  <std::endl; current++; > std::cout  <"\n Done\n"; > void initcreate_tree() using namespace boost::python; BOOST_PYTHON_MODULE(test)  def("create_tree", create_tree, ""); > 
// setup.py #!/usr/bin/env python from distutils.core import setup from distutils.extension import Extension setup(name="PackageName", ext_modules=[ Extension("test", ["test.cpp"], libraries = ["boost_python"]) ]) 

We then compile and run the module as follows:

$ python setup.py build $ cd build/lib* $ python >>> import test >>> test.create_tree() Window Query: 3,2.1:c 8,5.1:a Done >>>

Handling Python objects and errors [ edit | edit source ]

One can also handle more complex data, e.g. Python objects like lists. The attributes are accessed with the extract function executed on the objects «attr» function output. We can also throw errors by telling the library that an error has occurred and returning. In the following case, we have written a C++ function called «afunction» which we want to call. The function takes an integer N and a vector of length N as input, we have to convert the python list to a vector of strings before calling the function.

#include using namespace std; void _afunction_wrapper(int N, boost::python::list mapping)  int mapping_length = boost::python::extractint>(mapping.attr("__len__")()); //Do Error checking, the mapping needs to be at least as long as N if (mapping_length  N)  PyErr_SetString(PyExc_ValueError, "The string mapping must be at least of length N"); boost::python::throw_error_already_set(); return; > vectorstring> mystrings(mapping_length); for (int i=0; imapping_length; i++)  mystrings[i] = boost::python::extractchar const *>(mapping[i]); > //now call our C++ function _afunction(N, mystrings); > using namespace boost::python; BOOST_PYTHON_MODULE(c_afunction)  def("afunction", _afunction_wrapper); > 

Источник

Читайте также:  Add to cart function in php
Оцените статью