PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

[FIXED] How to append a temporary vector (defined at compile time) efficiently?

 May 12, 2022     append, c++, vector     No comments   

Issue

I have a std::vector<char> v that is created at runtime, and I would like to append {'a', 'k', 'e', 'e', 'f'} to it.

I could just do v.emplace_back on each individual letter, or I can create an l-value vector and store {'a', 'k', 'e', 'e', 'f'} and then use insert with iterators, but I don't like either of these approaches because the former requires additional lines (I have to do this in several parts of the code), and the letter requires creating an l-value vector (might be some efficiency issues)?

Is there a better way to do this? I'm essentially looking for a 1-2 liner, e.g., something like

v.emplace_back({'a', 'k', 'e', 'e', 'f'}); // doesn't work

I forgot to mention that v's capacity is reserved to accommodate this temporary vector -- this is probably not relevant, however?


Solution

vector::insert() has an overload that accepts a std::initializer_list as input, which can be constructed from a brace-list, eg:

v.insert(v.end(), {'a', 'k', 'e', 'e', 'f'});

Online Demo



Answered By - Remy Lebeau
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing