What is the C++ equivalent code of this Python slicing statement? - c++

I am trying to translate the following Python statements to C++:
some_array = [11, 22, 33, 44]
first, rest = some_array[0], some_array[1:]
What I have so far is this:
int array[4] = {11, 22, 33, 44};
vector<int> some_array (array, 4);
int first = some_array.front();
vector<int> rest = some_array;
rest.erase(rest.begin());
How can this be shorter and/or efficiently rewritten?
Can this be written without using C++ templates and/or vectors?
Is there an online service (or software) for translating such non-trivial Python code snippets to human readable C++ code?

This:
vector<int> rest = some_array;
rest.erase(rest.begin());
can be shortened to:
vector<int> rest(some_array.begin() + 1, some_array.end());
If you can use C++11, you can shorten the whole code to:
vector<int> some_array { 11, 22, 33, 44 };
int first = some_array.front();
vector<int> rest (some_array.begin() + 1, some_array.end());
Although I doubt this would be much of an advantage...

The simplest way of doing this is
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> arr = {11, 22, 33, 44};
int first = arr[0];
vector<int> rest;
for (int i = 1; i < arr.size(); i++) {
rest.push_back(arr[i]);
}
return 0;
}
Or you can do this in this way also,
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> arr = {11, 22, 33, 44};
int first = arr[0];
vector<int> rest(arr.begin() + 1, arr.end());
return 0;
}

Related

How to join a vector<int> to a single int in C++?

How would I convert a vector of ints into a single int in c++?
vector<int>myints = {3, 55, 2, 7, 8}
Expected answer: 355278
Here's a quick and dirty way:
using namespace std;
vector<int> myints = {3, 55, 2, 7, 8};
stringstream stream;
for(const auto &i : myints)
{
stream << i;
}
int value = stoi(stream.str());
And here's a way to do it without strings:
using namespace std;
vector<int> myints = {3, 55, 2, 7, 8};
int value = 0;
for(auto i : myints)
{
int number = i;
do
{
value *= 10;
i /= 10;
}while(i != 0);
value += number;
}
cout << value << endl;
The i /= 10 is the key bit here as it scales the number up based on the number of digits in the current number, i
Using the <string> library and the += operator you can iterate over the vector of ints, cast each number to a string and print out the result:
#include <vector>
#include <iostream>
#include <string>
using namespace std;
int main() {
vector <int> myints = {3, 55, 2, -1, 7, 8};
string s = "";
for(int i : myints){
s += to_string(i);
}
cout << s; //prints 3552-178
}
This should do the job. Please care that an int may not be enough to handle the number of digits.
#include <vector>
#include <sstream>
int vectorToSingleInt(const std::vector<int> &myints)
{
std::stringstream stringStream;
for (int &i : myints)
stringStream << i;
int output = 0;
stringStream >> output;
return output;
}
The trick is that you need to figure out how many digits each number contains. You can use log10 from <cmath> to do this. You can move the total by pow(10, x), where x is the number of digits you are adding:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main() {
vector<int>myints = {3, 55, 2, 7, 8};
int total = 0;
for (auto it = myints.begin(); it != myints.end(); ++it) {
int x = int(log10(*it)) + 1;
total = total * pow(10, x) + *it;
}
cout << total << endl;
return 0;
}
The output is 355278, as expected.
Here is an IDEOne link.

set multiple array variables at the same time (c++)

I'm trying to make an ASCII art using C++, and having some problems in arrays.
Is there any way to set multiple array variables at the same time?
Let me be more specific.
When you initialize an array, you can do this way.
int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
By the way shown above, you can set 10 array variables at the same time.
However, I want to (re) set some of the array variables like this?
a[1] = 3;
a[4] = 2;
a[5] = 2;
a[7] = 2;
Since there is NO rule in the variables, I can't do
for(int i=0; i<10; i++) a[i] = i+1;
fill(n);
I can't use an for statement or the fill, fill_n function, since there is no regularity.
To sum up,
Is there any way to set more than 1 array variables at the same time? (Like the second code snipplet above?
Given a index-value mapping list, and assign it one by one.
template<typename T, size_t N>
void Update(T(&arr)[N], const std::vector<std::pair<size_t, T>>& mappings)
{
for (const auto& mapping : mappings)
if(mapping.first < N)
arr[mapping.first] = arr[mapping.second];
}
int main()
{
int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Update(arr, { {1, 3}, {4, 2}, {5, 2}, {7, 2} });
return 0;
}
As far as I'm aware without a pattern a control structure is kind of redundant, you might be better served reading from a file.
// for user input
int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };
for (int i = 0; i < 10; i++) {
cout << "Please input your value for array index " << i << endl;
cin >> arr[i];
}
// for manual input in initalization
int arr[10] = { 0, 3, 2, 2, 2, 5, 6, 7, 8, 9 };
However a better approach might be to read it from a file, http://www.cplusplus.com/forum/general/58945/ Read "TheMassiveChipmunk"'s post there for exactly how to do it.
Assuming you know which indices you will be changing upfront you can use a separate index array:
int ind[4]= {1,4,5,7};
..and an accompanying array with values
int new_val[4] = {3,2,2,2};
The you can use the following for loop to assign the values:
for (int i=0; i<4; i++)
arr[ind[i]] = new_val[i];
You should also use some variable signifying the number of indices to be changed like int val_num = 4 instead of plain number 4.
Changes that are defined in runtime to an array can be easily implemented by using a list to save tuples that represent the changes you want to make. As an example, we can write:
#include <tuple>
#include <list>
#include <iostream>
using namespace std;
typedef tuple <int, int> Change;
int main() {
int a[5] = {1,2,3,4,5};
list<Change> changes;
//represents changing the 2-th entry to 8.
Change change(2,8);
changes.push_back(change);
for(auto current_change: changes)
a[get<0>(current_change)] = get<1>(current_change);
cout << a[2] << '\n';
}
Prints 8.

printing a 2D array inside a function in c++

I have made the following program in c++. I just want to print an array elements. My code is as follows:
#include <iostream>
#include <cstdio>
using namespace std;
#define n 5
double dist[n][n];
void read_distances()
{
for(int i = 0; i < n ; i++)
{
for (int j = 0 ;j < n; j++)
{
cout<<dist[i][j]<<" ";
}
cout<<"\n";
}
}
main()
{
double dist[n][n] =
{
{0, 20, 30, 10, 11},
{15, 0, 16, 4, 2},
{3, 5, 0, 2, 4},
{19, 6, 18, 0, 3},
{16, 4, 7, 16, 0}
};
read_distances();
}
I just wanted to print the dist[][] array inside the read_distances() function. But here I am getting all the values 0 as output. what's the reason of this?
The reason is because you declared the dist array in main(), and you initialized its contents, but the function read_distances() prints the values of a global array called dist. It happens to have the same name as the dist array in main()'s scope, but is a completely different array, and it is never initialized.
EDIT: you asked how to make it work. The easiest way is to pass it as a parameter. After removing the global declaration:
void read_distances(double dist[n][n])
{
// ...
}
and then in your main():
read_distances(dist);
(technically, the parameter to read_distances() is actually double (*)[n], but that's going to be a topic for another day and I didn't want to make this too confusing).
How about this:
#include <iostream>
#include <cstdio>
using namespace std;
#define n 5
void read_distances(double dist[n][n])
{
for(int i = 0; i < n ; i++)
{
for (int j = 0 ;j < n; j++)
{
cout<<dist[i][j]<<" ";
}
cout<<"\n";
}
}
int main()
{
double dist[n][n] =
{
{0, 20, 30, 10, 11},
{15, 0, 16, 4, 2},
{3, 5, 0, 2, 4},
{19, 6, 18, 0, 3},
{16, 4, 7, 16, 0}
};
read_distances(dist);
}
Your code doesn't work because you overshadowed the global version of dist with the local one you created at main. So you either not use a global one, like I do here, and pass the one you create at main() to your printing function; or you fill that array without creating a new array in main().

C++ equivalent to the python code: "for x in iterable:" [duplicate]

This question already has answers here:
What is the correct way of using C++11's range-based for?
(4 answers)
Closed 7 years ago.
I want to do in c++ something like in python would be:
nums=[31, 46, 11, 6, 14, 26]
nlttf=[]
for n in nums:
if n<25:nlttf.append(n)
That would be the Range-based for loop:
SomethingIteratable cont;
for (const auto &v : cont) {
// Do something
}
As usual, const auto &v gives you immutable references, auto &v mutable references and auto v mutable deep copies.
Beware: You may not do anything in the loop that invalidates iterators of the container you iterate.
If you have C++11 then the code is the following:
for (int n: iterator) { /*Do stuff with n*/ }
If you have C++11 or greater, then you can do it this way.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int num[] = {31, 46, 11, 6, 14, 26};
vector<int>nlttf;
for(int n:num){
if(n<25)nlttf.push_back(n);
}
return 0;
}
Read this Range-based for Statement (C++).
For std::vector see this and this link.
Here's another option, using C++11 and the boost libraries:
#include <iostream>
#include <boost/foreach.hpp>
#include <vector>
int main(){
std::vector<int> nums {31, 46, 11, 6, 14, 26};
std::vector<int> nltff;
BOOST_FOREACH(auto n, nums) if (n < 25) nltff.push_back(n);
BOOST_FOREACH(auto n, nltff) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Output:
11 6 14

How to efficiently fill-in a structure with vectors?

I am not expert in C++ but I believe this is not the most elegant solution:
#include <iostream>
#include <vector>
struct coord {
int x;
int y;
};
int main()
{ std::vector<int> a {1,2,3,4,5};
std::vector<int> b {10,20,30,40,50};
int i;
std::vector<coord> loc (5);
for (i=0;i<5;i++)
{ loc[i].x = a[i];
loc[i].y = b[i];
}
return 0;
}
Does anyone has a better solution ?
It looks like you are using C++11. While I'm not 100% sure this should work:
std::vector<coord> loc { {1, 10}, {2, 20}, {3, 30}, {4, 40}, {5, 50} };
What are you trying to accomplish by creating two vectors just to fill one vector? Your method is inefficient when it comes to declaring two independent vectors to assign into one single vector, and also messy. Remove the two vectors and set the values of your vector using brackets
= { {val1,val2} {val1,val2} {val1,val2} }
But if you would like to stick with your vector filling method and HAVE to use a vector, just one one vector that holds both the values of a and b and loop as such
//check to make sure size is even
for(int i = 0; i < vect.size(); i +=2)
{
vect[i].x = a[i];
vect[i].y = a[i+1];
}