C++ std::vectors with predefined sizes - c++

While taking a look at a solution for a problem, I came across this implementation of a vector.
const int MX = 100000;
std::vector <int> adj[MX];
The push_back() function doesn't work with this implementation of the vector class, and to add an element, the following code was used:
std::ifstream fin ("file.in");
int N = 5;
for (int i = 0; i < (N-1); i++) {
int A,B; fin >> A >> B; // reading values from another file
adj[A].pb(B), adj[B].pb(A);
}
The way this code is adding is adding pushing back a value to a certain part of the list, which I imagine as a vector inside the vector of the form:
{
{ },
{ }
}
In addition, how would I loop through this vector because for (int n : adj) does not work. I am not sure what the form of this vector is because this method of looping does not work.

What you have is C style array of vectors, off the bat you could replace that with std::array:
std::array<std::vector<int>, MX> adj;
To loop through these you would have to use a nested one, the outer loop to go through the array, and the inner one to go through each vector, something like this:
const int MX = 3;
//array of 3 vectors
std::array<std::vector<int>, MX> adj {{{1,2,3,4}, {5,6,7,8}, {9, 10, 11, 12}}};
for(auto &v : adj){ //for the array
for(auto i : v){ //for each vector
std::cout << i << " ";
}
std::cout << "\n";
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12
You can also access individual elements using C style indexing:
std::cout << adj[1][0]; // vector element index 0 of array index 1
Or in a safer way, using container member at:
std::cout << adj.at(1).at(0);
This would output 5.
You should be careful though, when randomly filling the array, an array is not meant to have empty elements, otherwise the loops will go through uninitialized array members, which is not ideal, perhaps you are looking for some other kind of container.

Related

Assign new vector to vector returned from function in C++

I have a function in C++ that takes a vector, and constructs a vector of the same size with modified values, then returns it:
vector<double> sigmoid_from_vector(vector<double> v){
int size = (v.size());//redundant but helps
vector<double> sigvec(size);//Create empty vector to store sigmoid values
for (int i = 1; i<=size; i++) {
sigvec[i] = 1/(1+exp(-1*v[i]));
//cout << "sig val calculated: " << sigvec[i] << endl;
}
return sigvec;
}
I cannot, for the life of me, use the returned vector. So for I have tried the following lines, that to my knowledge should work:
vector<double> testsig = sigmoid_from_vector(age_train);
vector<double> testsig = move(sigmoid_from_vector(age_train));
edit: I should go to bed. Thank you everyone
There are several problems with you given program.
Problem 1
Since you're using i<=size instead of i<size you'll go out of bound of the vector leadingto undefined behavior.
Additionally note that vector indexing starts from 0 and not 1 so you can replace int i = 1 with int i = 0.
Problem 2
Moreover, there is no need to create a separate vector named sigvec as v is already a local copy of the passed vector.
Thus the total changes are as follows:
vector<double> sigmoid_from_vector(vector<double> v){
//---------------v--------------------->0 instead of 1
for (int i = 0; i<size; i++) {
//-------------------^----------------->< instead of <=
//other code here using v instead of sigvec
}
return v;
}

How can I find the number of elements in an already declared array of size n, if it's partially filled?

Suppose I created an array of size 5. Filled two number 1 and 2 at index 0 and 1 respectively. Now I want to return number of elements currently present in the array, i.e. 2 and not 5 given by size below. How can I do that?
int arr[5];
arr[0] = 1;
arr[1] = 2;
//size returns 5 but I want it to return 2, since it has only 2 elements.
int size = sizeof(arr)/sizeof(arr[0]);
cout << size;
If you use a classic array, it is not possible to do what you say, you will get 5 outputs each time. But if you use std::vector, the size of the vector will change automatically every time you add a new element to the vector. Then, you can easily count the number of elements in the vector by using the size() function. you can print to the screen.
#include<iostream>
#include<vector>
int main() {
std::vector<int> vec;
for (size_t i = 1; i <= 2; ++i) { vec.push_back(i); }
std::cout << "number of elements= " << vec.size();
return 0;
}

initialize 2d vector in c++

So, I have the following code in c++:
This is the 2d vector:
vector<vector<int>> adj;
Initialization of 2d vector:
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(3);
adj[1].push_back(4);
adj[1].push_back(5);
Printing the vector:
for(auto i : adj) {
for(auto j : i)
cout << j << " ";
cout << endl;
}
Compilation is without error but when I try to run it shows nothing.
How to fix this?
When you write adj[0], you're implicitly assuming that the vector has a size of at least 1, in order for the zeroth element to exist. This is not the case for an empty vector, such as a newly initialized one. Unfortunately, this does not guarantee an error of any kind, it is Undefined Behavior, and the compiler is allowed to let literally anything happen. To avoid it, you need to make room for those elements, which can be done in a number of ways:
adj.resize(2); // now size == 2, and [0] and [1] can be safely accessed
adj[0].push_back(1);
adj[1].push_back(3);
or alternatively
adj.push_back({}); // append default-constructed vector
adj.back().push_back(1); // append 1 to the above vector
or, perhaps most concisely:
adj = {
{1, 2},
{3, 4, 5}
};
// adj now contains two vectors containing {1, 2} and {3, 4, 5} respectively
If you want to use the subscript [] operator for indexed access to a vector, consider using vector.at(), which performs the same functionality but throws an exception if the index is out of range. This can be very helpful for debugging.
You can initialize the size of the vector by calling its constructor:
vector< vector<int> > adj(row_size, vector<int>(col_size));
^^^ ^^^^^^^ ^^^
Dimension 1 Element Ctor Dimension 2
Then you can index it like an array.
std::vector operator[] expects an element to exist. It will result in undefined behavior if an undefined element is accessed. Push a std::vector to the outer vector before pushing int to the inner vector. The at() member can be used to safely access any array index with error handling.
#include <vector>
#include <iostream>
int main()
{
std::vector<std::vector<int>> adj(2); // add two std::vector<int>
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(3);
adj[1].push_back(4);
adj[1].push_back(5);
for(auto const & i : adj) {
for(auto const & j : i)
std::cout << j << " ";
std::cout << std::endl;
}
}

Create std::vector with brackets for default size

#include <iostream>
#include <vector>
int main()
{
static const unsigned TOTAL = 4;
std::vector<int> v[TOTAL];
v[2].push_back(37);
//std::cout << v.size(); error
std::cout << v[0].size();
std::cout << v[2].size();
return 0;
}
Is is valid to instatnitate std::vector with bracket like in the code above?
MSVS and ideone compile it just fine, but vector is messed up (see error line).
I know I can use resize, but what is going on here?
You are creating a TOTAL sized array of vectors.
What you need is
std::vector<int> v(TOTAL);
This constructs a vector with TOTAL zero-initialized ints.
Then,
std::cout << v.size() << std::endl; // prints 4
std::cout << v[0] << std::endl; // prints 0
and so on.
It is valid to instantiate std::vector with bracket like in the code, but with different meanings.
std::vector<int> v[TOTAL];
Here you defined a vector v of size=TOTAL, each element of which is a vector<int>. Initially, these TOTAL vector<int>s are all empty (i.e. size=0).
After you call v[2].push_back(37);, v[2] will become a vector<int> of size=1 with a value 37 in it.
So the output you for the following will be 0 and 1.
std::cout << v[0].size();
std::cout << v[2].size();
If you want to call size(), you should call v[i].size() or define it as vector<int> v(TOTAL); (v is a vector of size=TOTAL, each element of which is an int).
I know I can use resize, but what is going on here?
you are basicly creating an array of type std::vector<int>, just as in here:
int arr[TOTAL];
Is is valid to instatnitate std::vector with bracket like in the code above?
you can have an array of vectors, but from your post it is not what you are after.
If you want to give your vector some initial size then use
std::vector<int> v(TOTAL);
this will set initial size of your vector to TOTAL, and value initialize all elements (set them to zero).
But you might actually want to:
std::vector<int> v;
v.reserve(TOTAL); // this is not necessary
// v.size() is zero here, push_back will add elements starting from index 0
because in case of std::vector<int> v(TOTAL); your push_back will start adding from index TOTAL.

2D Vector with 3 columns and undeclared number of rows

How to declare a 2D Vector with following specifications:
Should have 3 columns (Ofcourse not actually but still)
Number of rows undeclared
Some suggest i should wrap an array inside a vector as below:
typedef array <float, 3> Point
vector <Point> 2DVector
But is there a way to use only vector to obtain the desired 2D Vector?
How to declare a 2D Vector with following specifications: [...]
A mix of std::vector and std::array is perfectly fine for the requirements:
using table = std::vector<std::array<float, 3>>;
table 2d_vector;
But is there a way to use only vector to obtain the desired 2D Vector?
Here it is:
using table = std::vector<std::vector<float>>;
table 2d_vector;
You'll have to be sure to only add 3 floats to the inner vectors though.
I need to return that vector to a function and the compiler doesn't seem to understand what is vector<array<float>>
Well, yes, of course it does not. std::vector<std::array<float>> does not name a type. You probably meant:
std::vector<std::array<float, 3>>;
// ^^^
Using an initializer_list could look like this;
First #include <initializer_list>
std::vector<std::initializer_list<float>> vec{ {1,2,3} };
vec.push_back( {4,5,6} ); // add a row
Accessing each element could be done like;
for (auto list: vec){
for(auto element: list){
std::cout<< element << " "; // access each element
}
std::cout<<"\n";
}
Getting at an individual element with (x, y) coords;
// access first row (y coord = 0), second element (x coord = 1, also the column)
std::cout<< "vec[0].begin() + 1 = (addr:" << (vec[0].begin() + 1)
<< " - value: " << *(vec[0].begin() + 1) << ')';
All of that together would output;
1 2 3
4 5 6
vec[0].begin() + 1 = (addr:0x40a0d4 - value: 2)
A cleaner way could be done like this;
// using a variable type of initializer_list
std::initializer_list<float> row = {1,2,3};
std::vector<std::initializer_list<float>> vec{ row };
row = {4,5,6}; // change list
vec.push_back(row); // add rows
vec.push_back({7,8,9});
for (auto list: vec){
for(auto value: list){
std::cout<< value <<" ";
}
std::cout<<"\n";
}
//access without looping
const float *element = vec[0].begin();
// pointer to first row, first element (value: 1)
element+=3;
// point to second row, first element (value: 4)
std::cout<<"\nElement("<<*element<<")\n";
// access the same element with x,y coords = (0,1)
int x = 0, y = 1;
std::cout<<"\ncoord(0,1) = "<< *(vec[y].begin() + x) << "\n";
Would output;
1 2 3
4 5 6
7 8 9
Element(4)
coord(0,1) = 4
Problems i can think of with this (assuming it's of any worth) are that;
1) the data is initialized as constant floats and as far as i know you cannot change them.and
2) if you change the list to equal {0,1,2,3,4,5} you now have more than 3 columns.