What is the easiest way to initialize a std::vector with hardcoded elements?
One method would be to use the array to initialize the vector
static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
What is the easiest way to initialize a std::vectorMyClass with hardcoded elements?
Aggregate initialization used for aggregate types as arrays:
string course_names[] = {"Linux", "C++", "HTML", "HTML5", "NodeJS", "Shell", "Python"};
Is different to initializer_list
initialization. std::vector
offers a constructor that takes in a std::initializer_list<T>
, and that's the constructor called when you try to initialize a vector
with braces. For this to work properly, you need extra braces for each element:
std::vector<Course> course_vector = {{"Linux"},
{"C++"},
{"HTML"},
{"HTML5"},
{"NodeJS"},
{"Shell"},
{"Python"}};
Also I it would be better to change your constructor to:
Course::Course(std::string const &s) : id(id_generator++), name(s) { }
Live Demo
Is it possible to initialize new std::vector in one line?
I just wonder if is possible to new and initialize a
std::vector
at
the same time, something like, do the two things in one line?
Yes, you can, via std::initializer_list
constructor10 of std::vector
constexpr vector( std::initializer_list<T> init,
const Allocator& alloc = Allocator() ); (since C++20)
With you can write
std::vector<int>* vec = new std::vector<int>{3, 4};
Because I need a vector that create on heap!
The terms we use in C++ are automatic and dynamic storage. In most of the cases, you do not require the std::vector<int>
to be allocated dynamically, rather the elements to be there. For this, you need simply a vector of integers.
std::vector<int> vec {3, 4};
However, if you're meant for a multidimensional vector, then I will suggest having a vector of vector of inters:
std::vector<std::vector<int>> vec{ {3, 4} };
When the inner vector has the same number of length, keep a single std::vector
and manipulate the indexes for acting as a two-dimensional array.
In both cases, the std::vector
in the background does the memory management for you.
c++ std vector initialize with existing objects
Is there a vector constructor or another technique to initialize the vector with only 1 copy?
If you move the local objects into an array, you can construct the vector from that array, eg:
// local objects
Location locs[3]{ {1, 2}, {3, 4}, {5, 6} };
// code that updates locs ...
// construct vector
std::vector<Location> pointsVec {locs, locs+3};
Online Demo
Another option would be to simply get rid of the local objects altogether, construct them inside the vector
to begin with, and then just refer to those elements, eg:
// construct vector
std::vector<Location> pointsVec{ {1, 2}, {3, 4}, {5, 6} };
// local objects
Location &l1 = pointsVec[0];
Location &l2 = pointsVec[1];
Location &l3 = pointsVec[2];
// code that updates l1, l2, l3 ...
create vector with new elements
Problem summary:
In the line
graph = new vector<vector<tuple<string, double>*>*>(67, new vector< tuple<string,double>*>());
constructor 3 of std::vector
is used (reference)
This will evaluate new vector<tuple<string,double>*>()
once, then create a vector with 67
copies of this pointer.
Solution:
Don't use pointers unless you have a really good reason to do so. Use
vector<vector<tuple<string, double>>> graph;
then you could simply do
graph.resize(67);
to insert 67 default constructed values. No pointers needed.
Maybe you are used to languages where new
is frequently used, but you shouldn't do that in C++. std::vector
and std::string
are fairly small objects that manage an underlying dynamic array. Creating pointers to them is usually not what you want and might also decrease performance.
3 dimensional vector in c++
The method of initialisation is
vector< vector < vector<Object>>> Vector3d(n,vector<vector<Object>(m))
This will work, as it will initialize the first dimension's size as n, which would contain n
no of vector<vector<Object>(m)
which is the default value. Now the size of the second dimension is defined as m, which has no initial value, hence you can append any vector to the second dimension space.
i.e.
vector<Object> v;
Vector3d[i][j].push_back(v);
where i and j are the indexes of the first 2 dimensions
i am unable to initilize vector with initilize elements
Thanks @BoP.
I have just changed my settings to c++14 and it worked image.
(C++ vectors) How to assign values in a range of elements inside a vector?
Just use a simple iterative loop, eg:
std::vector<int> v = {0, 0, 0, 0, 0};
for(size_t i = 1; i <= 3; ++i) {
v[i]++;
}
Online Demo
Which you can also replicate using standard library algorithms like std::for_each()
and std::transform()
, eg:
std::vector<int> v = {0, 0, 0, 0, 0};
std::for_each(v.begin()+1, v.begin()+4,
[](int& i){ ++i; }
);
Online Demo
std::vector<int> v = {0, 0, 0, 0, 0};
std::transform(v.begin()+1, v.begin()+4, v.begin()+1,
[](int i){ return i+1; }
);
Online Demo
Assigning to std::array element in std::vector of arrays fails
You are working on a copy of the array, you need a reference to the array in the vector
int main() {
vector<array<int, 1>> v;
array<int, 1> a = { 99 };
v.push_back(a);
cout << v[0][0];
auto& ar = v[0];
ar[0] = 42;
cout << v[0][0];
}
gives
99 42
Related Topics
What Does Int Argc, Char *Argv[] Mean
Why Do We Need Virtual Functions in C++
What Are the Differences Between Struct and Class in C++
Capture Characters from Standard Input Without Waiting For Enter to Be Pressed
Why Can't Variables Be Declared in a Switch Statement
When Should I Write the Keyword 'Inline' For a Function/Method
How to Get the List of Files in a Directory Using C or C++
Start Thread With Member Function
What Is the "--≫" Operator in C++
Is Gcc 4.8 or Earlier Buggy About Regular Expressions
How to Detect Unsigned Integer Overflow
C++11 Std::To_String(Double) - No Trailing Zeros
Why Should I Not #Include ≪Bits/Stdc++.H≫
Automatically Add All Files in a Folder to a Target Using Cmake