Cannot predetermine values for a vector - c++

I'm using sublime text for C++ and, for some reason, I am not able to predetermine values for a vector.
std::vector<int> v = {1,2,3,4,5};
Whenever I do such a thing, I get this error:
'std::vector<int>' cannot be initialized with an initializer list
std::vector<int> v = {1,2,3,4,5};
^ ~~~~~~~~~~~

Maybe try this : std::vector v{1,2,3,4,5}; ?

Maybe try this, please
#include <iostream> // std::cout
#include <numeric> // std::iota
#include <vector> // std::vector
// Driver code
int main()
{
std::vector<int> v(6);
std::iota(v.begin(), v.end(), 1);
std::cout << "Elements are :";
for (auto i : v)
std::cout << ' ' << i;
std::cout << '\n';
return 0;
}
Output:
Elements are : 1 2 3 4 5 6

This directly answers your question:
std::vector<int> v;
for(int i=0; i<6; i++)
{
v.push_back(i);
}
To be more generic, checkout:
int myints[] = {16,2,77,29};
std::vector<int> v (myints, myints + sizeof(myints) / sizeof(int) );
Finally print the results with an iterator:
std::vector<int>::iterator vi;
for(vi = v.begin(); vi != v.end(); ++vi)
std::cout << *vi;
One more option would be to push_back() every different value you want.

Related

How to point the iterator to an element in a vector which is greater than or equal to a target number

For example, I have a vector as v=[7,4,5,10,13]. Here my target number is 6.
I am first sorting the vector with:
sort(v.begin(), v.end());
Now my output would be [4,5,7,10,13]. After this, I want to print the numbers greater than or equal to '6', which will give me output as [7,10,13].
What's a convenient way in C++ to perform this task?
Use std::upper_bound:
#include <algorithm>
#include <vector>
#include <iostream>
int main()
{
std::vector<int> v = {7,4,5,10,13};
std::sort(v.begin(), v.end());
auto iter = std::upper_bound(v.begin(), v.end(), 6);
for (; iter != v.end(); ++iter)
std::cout << *iter << " ";
}
Output:
7 10 13
This is my quick solution
std::vector<int> v = {7,4,5,10,13};
std::sort(v.begin(), v.end());
std::copy_if(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "),
[](int a){ return a > 6;})
Or if you compiler already supports it use
#include <algorithm>
#include <ranges>
#include <vector>
#include <iostream>
auto larger_then_6 = [](int i) { return i > 6; };
int main()
{
std::vector<int> v = { 7,4,5,10,13 };
std::sort(v.begin(), v.end());
for (auto value : v | std::views::filter(larger_then_6))
{
std::cout << value << " ";
}
std::cout << std::endl;
}

Suppose we have two std::vectors v1 and v2 and we dont want to combine these in a struct. How to transform v2 the same way v1 was transformed by sort?

This is a followup of this question. The only difference is the constrain that the two vectors cannot be combined in a struct.
Suppose we have a vector
std::vector<double> v1 = {9.0,5.0,3.0,2.0,1.0};
Now we sort the vector v1. Let v2 be given by
std::vector<std::string> v2 = {"you?","are","how","there","hello"};
How to transform v2 the same way v1 was transformed by sort?
Based on this answer, you can use an array of indices to "sort" the vector of doubles, and just use the resulting index array to index the vector of strings.
#include <algorithm>
#include <iostream>
#include <string>
#include <numeric>
int main()
{
std::vector<double> v1 = {5.0,9.0,3.0,2.0,1.0};
std::vector<std::string> v2 = {"are", "you?","how","there","hello"};
// Create an array of indices, starting from 0
std::vector<int> index(v1.size());
std::iota(index.begin(), index.end(), 0);
// "Sort" the index array according to the value in the vector of doubles
std::sort(index.begin(), index.end(),
[&](int n1, int n2){ return v1[n1] < v1[n2]; });
// Output results
for (auto i : index )
std::cout << v2[i] << " " << v1[i] << ", index is " << i << "\n";
}
Output:
hello 1, index is 4
there 2, index is 3
how 3, index is 2
are 5, index is 0
you? 9, index is 1
Note:
I changed the original data to illustrate how the index array works.
The abstraction you are missing is the ability to view the vectors as one item. That's the role that a vector of indices is a proxy for in another answer.
I think it is worth mentioning that there are libraries that provide such a concept (often under the name "zip"). For example, with range-v3:
std::vector<double> v1 = {5, 9, 3, 2, 1};
std::vector<std::string> v2 = {"are", "you?", "how", "there", "hello"};
// Sort the vectors
ranges::actions::sort(ranges::views::zip(v1, v2));
// Output results
for (std::size_t i = 0; i < v1.size(); ++i)
std::cout << v2[i] << " " << v1[i] << ", index is " << i << "\n";
A possible solution uses a helper std::vector<int>:
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
template<typename T>
void MySort(std::vector<T> t, std::vector<int>& helper)
{
struct StructHelper
{
T t1;
int num;
StructHelper(T t, int i): t1{t}, num{i} {};
bool operator<(const StructHelper& other) const
{ return t1 < other.t1; }
};
std::vector<StructHelper> shVector;
for(int i=0; i<t.size(); ++i)
{
shVector.emplace_back(t[i], i);
}
std::sort(shVector.begin(), shVector.end());
helper = std::vector<int>(t.size());
for(int i=0; i<t.size(); ++i)
{
helper[i] = shVector[i].num;
}
}
template<typename T>
void MySortUsingHelper(std::vector<T>& t1, const std::vector<int>& helper)
{
if(t1.size() != helper.size()) throw std::out_of_range("not same size");
std::vector<T> t2(t1.size());
for(int i=0; i<helper.size(); ++i)
{
t2[i] = t1[helper[i]];
}
t1 = t2;
}
int main() {
std::vector<double> v1 = {9.0,5.0,3.0,2.0,1.0};
std::vector<int> helper;
MySort(v1, helper);
std::vector<std::string> v2 = {"you?","are","how","there","hello"};
MySortUsingHelper(v2, helper);
for(auto elem : v2)
{
std::cout << elem << " ";
}
return 0;
}
You can run the above code online to see the following output:
hello there how are you?

Vector comparison

Vector function emplace()
My emplace function does not work. Any help would be appreciated
vector <int> vec1;
vector <int> vec2(4,0);
vector <int>::iterator iter1;
vector <int>::iterator iter2;
srand(time(NULL));
for(i=0; i<5; i++){
n =rand()%10+1;
vec1.push_back(n);
}
for(iter1=vec1.begin();iter1<vec1.end();iter1++){
for(iter2=vec2.begin();iter2<vec2.end();iter2++){
if(*iter1<=*iter2){
//vec2.emplace(iter1,*iter1);
//print();
}
}
}
for(iter2=vec2.begin();iter2<vec2.end();iter2++){
Because vec2 starts populated with four values of 0, you will never find an element where *iter1 <= *iter2 unless *iter1 == 0.
Instead of zero-initializing it to avoid allocations, you want to reserve space.
vec2.reserve(vec1.size());
and then instead of a for loop you can use std::lower_bound to find the insert location:
#include <iostream>
#include <vector>
#include <algorithm>
void print_vec(const char* label, const std::vector<int>& vec) {
std::cout << label << ": ";
for (int v : vec) {
std::cout << v << ", ";
}
std::cout << "\n";
}
int main() {
std::vector <int> vec1 { 4, 1, 2, 2, 5 };
std::vector <int> vec2;
print_vec("v1", vec1);
vec2.reserve(vec1.size());
for (int v : vec1) {
auto it = std::lower_bound(vec2.begin(), vec2.end(), v);
if (it == vec2.end() || *it != v)
vec2.emplace(it, v);
print_vec("v2", vec2);
}
print_vec("Fin", vec2);
return 0;
}
Live demo: http://ideone.com/o5td9K
What you are trying to do is like insertion sort.
https://en.wikipedia.org/wiki/Insertion_sort
has the pseudo-code. At each step you will check every element in vector 2 and place the new element where it belongs (while loop).

Getting Value from particular index in 2d vector in c++

I have made a 2d vector using :
std::vector<std::vector<int> *> hp;
I want to initialise hp vector and get the data from particular index for the same.
for eg,
Getting the values from hp[2][2];
Please do help
Try the following
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<int> *> hp =
{
new std::vector<int> { 1, 2, 3 },
new std::vector<int> { 4, 5, 6 }
};
for ( std::vector<std::vector<int> *>::size_type i = 0;
i < hp.size(); i++ )
{
for ( std::vector<int>::size_type j = 0; j < hp[i]->size(); j++ )
{
std::cout << ( *hp[i] )[j] << ' ';
// std::cout << hp[i]->operator[]( j ) << ' ';
}
std::cout << std::endl;
}
for ( auto &v : hp ) delete v;
return 0;
}
For commented and uncommented statements within the inner loop the program output will be the same and look like
1 2 3
4 5 6
Note that
std::vector<std::vector<int>*> hp
defines a std::vector containing pointers to objects of type
std::vector<int>
As ravi mentioned, you probably want
std::vector<std::vector<int>> hp;
But if you insist on having a vector with pointers,
std::vector<std::vector<int>*> hp;
(*hp[2])[2] // retrieves third value from third std::vector<int>
Remark: In C++11 (also called C++0x) you don't need the spacing between the ">" (as I wrote in the examples).
If these are pointers to vectors that are owned elsewhere:
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
// Create owning vector
std::vector<std::vector<int>> h = {{0,1,2},{3,4,5},{6,7,8}};
// Create vector of pointers
std::vector<std::vector<int>*> hp(h.size());
//auto get_pointer = [](std::vector<int>& v){return &v;}; // C++11
auto get_pointer = [](auto& v){return &v;}; // C++14
std::transform(h.begin(), h.end(), hp.begin(), get_pointer);
// Output value in third column of third row
std::cout << (*hp[2])[2];
}

swap array values in c++

I want to shift left array values if my v=4 is in a[n],remove 4 from a[n] and at the end index add 0,how i can do this?
#include <iostream>
using namespace std;
const int n=5;
int main()
{
int a[n]={1,5,4,6,8}, v=4;
int b[n];
cout << "Enter a Value" << endl;
cout<<v<<endl;
for(int i=0; i<n; i++){
cout<<a[i];
}
cout<<endl;
for(int j=0; j<n; j++){
b[j]=a[j];
if(a[j]==v)
b[j]=a[++j];
cout<<b[j];
}
return 0;
}
#include <vector> // needed for vector
#include <algorithm> // needed for find
#include <iostream> // needed for cout, cin
using namespace std;
// Vectors are just like dynamic arrays, you can resize vectors on the fly
vector<int> a { 1,5,4,6,8 }; // Prepare required vector
int v;
cout << "enter value"; // Read from user
cin >> v;
auto itr = find( a.begin(), a.end(), v); // Search entire vector for 'v'
if( itr != a.end() ) // If value entered by user is found in vector
{
a.erase(itr); // Delete the element and shift everything after element
// Toward beginning of vector. This reduces vector size by 1
a.push_back(0); // Add 0 in the end. This increases vector size by 1
}
for( int i : a ) // Iterate through all element of a (i holds element)
cout << i; // Print i
cout << '\n'; // Line end
a few helpful links:
vector , find , iterator , erase , push_back
You could use std::rotate. I suggest that you use std::vector instead of C arrays and take full advantage of the STL algorithms. Nevertheless, below I'm illustrating two versions one with C arrays and one with std::vector:
Version with C array:
#include <iostream>
#include <algorithm>
int main()
{
int const n = 5;
int a[n] = {1,5,4,6,8};
std::cout << "Enter a Value" << std::endl;
int v;
std::cin >> v;
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
auto it = std::find(std::begin(a), std::end(a), v);
if(it != std::end(a)) {
std::rotate(it + 1, it, std::end(a));
a[n - 1] = 0;
}
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
return 0;
}
Version with vector:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> a{1,5,4,6,8};
std::cout << "Enter a Value" << std::endl;
int v;
std::cin >> v;
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
auto it = std::find(std::begin(a), std::end(a), v);
if(it != std::end(a)) {
std::rotate(it + 1, it, std::end(a));
a.back() = 0;
}
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
return 0;
}
Here's an example using std::array
#include <array>
#include <algorithm>
// defines our array.
std::array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
// find the position of the element with the value 4.
auto where = std::find(a.begin(), a.end(), 4);
// if it wasn't found, give up
if (where == a.end())
return 0;
// move every element past "where" down one.
std::move(where + 1, a.end(), where);
// fill the very last element of the array with zero
a[ a.size() - 1] = 0;
// loop over our array, printing it to stdout
for (int i : a)
std::cout << i << " ";
std::cout << "\n";
Why would anyone use these awkward algorithms? Well, there are a few reasons. Firstly, they are container-independant. This will work with arrays and vectors and deques, no problem. Secondly, they can be easily used to work with a whole range of elements at once, not just single items, and can copy between containers and so on. They're also type-independant... you acn have an array of strings, or an vector of ints, or other more complex things, and the algorithms will still work just fine.
They're quite powerful, once you've got over their initial user-unfriendliness.
You can always use either std::array or std::vector or whatever without using the standard library algorithms, of course.
std::array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
size_t where = 0;
int to_remove = 4;
// scan through until we find our value.
while (a[where] != to_remove && where < a.size())
where++;
// if we didn't find it, give up
if (where == a.size())
return 0;
// shuffle down the values
for (size_t i = where; i < a.size() - 1; i++)
a[i] = a[i + 1];
// set the last element to zero
a[ a.size() - 1] = 0;
As a final example, you can use memmove (as suggested by BLUEPIXY) to do the shuffling-down operation in one function call:
#include <cstring>
if (where < a.size() - 1)
memmove(&a[where], &a[where + 1], a.size() - where);