Can we do something like this using c++ STLs. If yes, how am I going to initialize the elements? I was trying to do this but it isn't working.
pair<vector<int>,vector<int>>p;
p.first[0]=2;
Can we do something like this using c++ STLs
Yes. Although, you are probably using the standard library instead.
If yes, how am I going to initialize the elements?
You initialize the elements the same way you initialize the elements of a vector that isn't in a pair. List-initialization is a neat option.
I was trying to do this but it isn't working.
You are trying to modify an element of the vector that you never put there. Take a look at the page that desribes what the operator[] does. It doesn't state that it adds elements to the vector. There are however, other functions that do.
Per default the vectors do not have any size, so you should either push_back
some elements or resize
them first. A way to initialize your p would be:
pair<vector<int>, vector<int>> p = {{1,2,3}, {4,5,6}};
p.first
and p.second
(with type std::vector<int>
) will be initialized, but they're still empty, there's no elements in them. Then p.first[0] = 2;
will lead to UB.
You might want
p.first.push_back(2);
Yes it works, but you have to allocate memory to the std::vector
s before you access their elements:
//p now can hold 1 element
p.first.resize(1);
Alternatively, you can use push_back
:
//p now has 1 element with value 2
p.first.push_back(2).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.