How would I fill a vector with the numbers from 1 to 10 in C++? I have this but its not working.
vector<int>test(10);
test={ 1, 10 };
Another using generate:
vector<int>test(10);
int x = 0;
std::generate(test.begin(), test.end(), [&]{ return x++; });
You can use std::iota():
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 1);
Many options. For example,
vector<int> test{1,2,3,4,5,6,7,8,9,10};
or
std::vector<int> test;
test.reserve(10); // prevent some reallocations
for (int i = 1; i < 11; ++i)
test.push_back(i);
or
std::vector<int> test(10);
std::iota(test.begin(), test.end(), 1);
vector<int> vInts;
for (int i=1;i<=10;++i){
vInts.push_back(i);
}
You could use standard algorithm std::iota declared in header <numeric> For example
#include <numeric>
#include <vector>
//...
std::vector<int> v( 10 );
std::iota( v.begin(), v.end(), 1 );
Related
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.
I am trying to solve this challenge from testdome. I think my approach to the solution is not optimal (or even correct). But before changing my approach I was wondering is it possible to return a vector of pairs? if yes, how?.
Below you will see the challenge, and afterwards my code.
Thank you.
#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>
std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
int tracker = list.size();
std::pair <int, int> result;
std::vector <std::pair <int,int>> list1(100);
for (int i = 0; i < (int)list.size(); i++){
for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){
if (list[i]+list[j] == sum)
list1.push_back(std::make_pair(list[i], list[j]) );
}
tracker--;
}
return list1; // I am stuck here
//throw std::logic_error("Waiting to be implemented");
}
#ifndef RunTests
int main()
{
std::vector<int> list = {3, 1, 5, 7, 5, 9};
std::pair<int, int> indices = findTwoSum(list, 10);
std::cout << indices.first << '\n' << indices.second;
}
#endif
EDIT
Initially, this was my solution. But once I posted it on testdome, I am getting zero correct answers out of 4 categories. It is test number 5. That is why I thought, returning only one answer was wrong.
#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>
std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
int tracker = list.size();
std::pair <int, int> result;
std::vector <std::pair <int,int>> list1(100);
for (int i = 0; i < (int)list.size(); i++){
for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){
if (list[i]+list[j] == sum)
return result=std::make_pair(list[i], list[j]);
}
tracker--;
}
return std::make_pair(-1,-1);
//throw std::logic_error("Waiting to be implemented");
}
#ifndef RunTests
int main()
{
std::vector<int> list = {3, 1, 5, 7, 5, 9};
std::pair<int, int> indices = findTwoSum(list, 10);
std::cout << indices.first << '\n' << indices.second;
}
#endif
Use can do this:
std::vector<std::pair<int, int> >findTwoSum(const
std::vector<int>& list, int sum)
{
int tracker = list.size();
std::pair <int, int> result;
std::vector <std::pair <int,int>> list1(100);
/* ...*/
return list1;
}
int main()
{
std::vector<int> list = {3, 1, 5, 7, 5, 9};
auto indices = findTwoSum(list, 10);
std::cout << indices[0].first << '\n' << indices[0].second;
}
You can simply use std::vector<std::pair<int, int>> as the return value of your function. (and not only std::pair<int, int> as you've done in your example)
So your function becomes:
std::vector<std::pair<int, int>> findTwoSum(const std::vector<int>& list, int sum) { ... }
you just need to switch the function signature to
std::vector<std::pair<int, int>> findTwoSum(const std::vector<int>& list, int sum)
But in the main you are assigning it to a pair, so you need also to change this:
std::pair<int, int> indices = findTwoSum(list, 10); // from
std::vector<std::pair<int, int>> indices = findTwoSum(list, 10); // to
std::vector<std::pair<int, int>> indices { findTwoSum(list, 10) }; // but this is better because you call just one constructor instead of a default constructor and a copy constructor
If you want to return a vector of pairs, your function signature should look like
std::vector<std::pair<...>> f();
Your current function is just returning a single std::pair.
If you are using C++17, you have two options:
use auto return type deduction
auto create_vector_of_pairs() {
std::vector<std::pair<int, int>> v;
v.emplace_back(1, 2);
v.emplace_back(3, 4);
v.emplace_back(5, 6);
return v;
}
use std::vector<std::pair<...>> as return type
std::vector<std::pair<int, int>> create_vector_of_pairs() {
std::vector<std::pair<int, int>> v;
v.emplace_back(1, 2);
v.emplace_back(3, 4);
v.emplace_back(5, 6);
return v;
}
Then, whatever option from above you choose, in your main function you could do something like:
std::vector<std::pair<int, int>> v = create_vector_of_pairs();
or
auto v = create_vector_of_pairs();
If I have an integer vector (std::vector) is there an easy way to convert everything in that vector to a char array(char[]) so (1,2,3) -> ('1','2','3')
This is what I have tried, but it doesn't work:
std::vector<int> v;
for(int i = 1; i < 10; i++){
v.push_back(i);
}
char *a = &v[0];
std::transform is the right tool for the job :
std::vector<int> iv {1, 2, 3, 4, 5, 6};
char ca[10] {};
using std::begin;
using std::end;
std::transform(begin(iv), end(iv), begin(ca), [](int i) { return '0' + i; });
If you don't need ca to be a C-style array, I'd recommend using std::array or std::vector instead. The latter needs std::back_inserter(ca) in place of begin(ca).
It can be as simple as this
std::vector<int> v { 1, 2, 3 };
std::vector<char> c;
for( int i : v ) c.push_back( '0' + i );
to realize why your way does not work you need to learn how integers and symbls represented on your platform.
Why not store it in char vector initially?
std::vector<char> v;
for(int i = 1; i < 10; i++){
v.push_back(i + '0');
}
Trick from: https://stackoverflow.com/a/2279401/47351
You can use std::transform with std::back_inserter, maybe something like this:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> vI{0,1,2,3,4,5,6,7,8,9};
std::vector<char> vC;
std::transform(vI.begin(), vI.end(), std::back_inserter(vC), [](const int &i){ return '0'+i; });
for(const auto &i: vC)
{
std::cout << i << std::endl;
}
return 0;
}
If you've already got the numbers in a vector then you can use std::transform and a back_inserter:
std::vector<int> v;
std::vector<char> c;
std::transform(v.begin(), v.end(), std::back_inserter(c), [](int i){return '0' + i;});
However, why not just say:
std::vector<char> v;
for(char i = '0'; i < '9'; i++)
{
v.push_back(i);
}
I am trying to find a way to copy elements of a vector to another vector.
int main()
{
std::vector<int> aVec{0,1,2,3,4};
std::vector<int>::iterator itBegin = aVec.begin();
std::vector<int>::iterator itEnd = aVec.begin()+3;
std::vector<int> aVecNew;
// How to insert elements ranging from itBegin till itEnd(including itEnd) to
// the vector aVecNew
return 0;
}
Most of the insert methods appear not to include itEnd. Is there a clean way to do this?
EDIT: If I am not sure ++itEnd is the end iterator or not. In such case it would fail. Is there any safer way without the mess ?
You can use std::copy from <algorithms> and std::back_inserter from <iterator>:
int main(int a, char**){
std::vector<int> aVec{ 0, 1, 2, 3, 4 };
std::vector<int>::iterator itBegin = aVec.begin();
std::vector<int>::iterator itEnd = aVec.begin() + 3;
std::vector<int> aVecNew;
std::copy(itBegin, itEnd, std::back_inserter(aVecNew));
return 0;
}
PS: Also, as it was mentioned in the comment, this code copies excluding itEnd. If you want to copy elements including itEnd, just increment its value by 1:
int main(int a, char**){
std::vector<int> aVec{ 0, 1, 2, 3, 4 };
std::vector<int>::iterator itBegin = aVec.begin();
std::vector<int>::iterator itEnd = aVec.begin() + 3;
std::vector<int> aVecNew;
std::copy(itBegin, ++itEnd, std::back_inserter(aVecNew));
return 0;
}
Some documentation on back_inserter and copy.
Beyond the ways already mentioned, std::vector has a constructor that will do exactly what you want (take the elements from range given begin and end iterators).
std::vector<int> aVecNew(itBegin, ++itEnd);
In the general case - the target vector does already exist - the copy onto a back_insert_iterator until just before ++itEnd is the right way, but in your case,
std::vector<int> aVecNew(itBegin, ++itEnd);
is the appropriate measure. std::vector has ctor #(4) for that; no reason to first create and then populate the vector here.
#include <vector>
#include <iostream>
#include <iterator> // ostream_iterator
#include <algorithm> // copy
int main()
{
std::vector<int> aVec{0,1,2,3,4}; // this is c++ of 2011 or later...
// ... thus this
std::vector<int>::iterator itBegin = aVec.begin();
std::vector<int>::iterator itEnd = aVec.begin() + 3;
// (if used) would at least be a case for "auto"
std::vector<int> aVecNew(itBegin, ++itEnd);
std::copy(aVecNew.begin(), aVecNew.end(),
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return EXIT_SUCCESS;
}
output:
0 1 2 3
live at Coliru's
Say I have a vector with values [1,2,3,4,5,6,7,8,9,10]. I want to create a new vector that refers to, for example, [5,6,7,8]. I imagine this is just a matter of creating a vector with pointers or do I have to push_back all the intermediary values I need?
One of std::vector's constructor accepts a range:
std::vector<int> v;
// Populate v.
for (int i = 1; i <= 10; i++) v.push_back(i);
// Construct v1 from subrange in v.
std::vector<int> v1(v.begin() + 4, v.end() - 2);
This is fairly easy to do with std::valarray instead of a vector:
#include <valarray>
#include <iostream>
#include <iterator>
#include <algorithm>
int main() {
const std::valarray<int> arr={0,1,2,3,4,5,6,7,8,9,10};
const std::valarray<int>& slice = arr[std::slice(5, // start pos
4, // size
1 // stride
)];
}
Which takes a "slice" of the valarray, more generically than a vector.
For a vector you can do it with the constructor that takes two iterators though:
const std::vector<int> arr={0,1,2,3,4,5,6,7,8,9,10};
std::vector<int> slice(arr.begin()+5, arr.begin()+9);
You don't have to use push_back if you don't want to, you can use std::copy:
std::vector<int> subvector;
copy ( v1.begin() + 4, v1.begin() + 8, std::back_inserter(subvector) );
I would do the following:
#include <vector>
#include <iostream>
using namespace std;
void printvec(vector<int>& v){
for(int i = 0;i < v.size();i++){
cout << v[i] << " ";
}
cout << endl;
}
int main(){
vector<int> v;
for(int i = 1;i <= 10;i++) v.push_back(i);
printvec(v);
vector<int> v2(v.begin()+4, v.end()-2);
printvec(v2);
return 0;
}
~