the data method of vector has some wrong - c++11

I use the data method of vector in C++, but I have some problems, the code is in belows:
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (5);
int* p = myvector.data();
*p = 10;
++p;
*p = 20;
p[2] = 100;
std::cout << "myvector contains:";
for (unsigned i=0; i<myvector.size(); ++i)
std::cout << ' ' << myvector[i];
std::cout << '\n';
return 0;
}
the result is myvector contains: 10 20 0 100 0, but why the result is not myvector contains: 10 20 100 0 0, the first one *p = 10; is 10, the second one ++p;*p = 20; is 20, that's all right, but the third one p[2] = 100; should be 100, but it is 0, why?

With visuals:
std::vector<int> myvector (5);
// ---------------------
// | 0 | 0 | 0 | 0 | 0 |
// ---------------------
int* p = myvector.data();
// ---------------------
// | 0 | 0 | 0 | 0 | 0 |
// ---------------------
// ^
// p
*p = 10;
// ----------------------
// | 10 | 0 | 0 | 0 | 0 |
// ----------------------
// ^
// p
++p;
// ----------------------
// | 10 | 0 | 0 | 0 | 0 |
// ----------------------
// ^
// p
*p = 20;
// ----------------------
// | 10 | 20 | 0 | 0 | 0 |
// ----------------------
// ^
// p
p[2] = 100;
// -------------------------
// | 10 | 20 | 0 | 100 | 0 |
// -------------------------
// ^ ^
// p p[2]
It's helpful to remember that p[2] is a shorter way to say *(p + 2).

Because you are modifying p itself.
After ++p (which I remember you it's equivalent to p = p + 1), p points to the element at index 1, so p[2] points at element at index 3 from the beginning of the vector which is why the fourth element is changed instead.

After ++p, pointer p is pointing to myvector[1].
Then we have:
p[0] pointing to myvector[1]
p[1] pointing to myvector[2]
p[2] pointing to myvector[3]

Related

ARM MMU Debugging

I have been working on a bare metal raspberry pi project, and I am now attempting to initialize the memory management unit, following the documentation and examples.
When I run it, however, on the pi, nothing happens afterwards, and when I run it in QEMU using gdb, gdb either crashes of I get a Prefetch Abort as exception 3. Have I incorrectly set some properties such as shareability, or incorrectly used isb, or is there something I have missed?
Here is my code below
pub unsafe fn init_mmu(start: usize) {
let tcr_el1 =
(0b10 << 30) | //4kb Granule
(0b10 << 28) | //TTBR1 outer shareable
(25 << 16) | //TTBR1 size
(0b10 << 12) | //TTBR0 outer shareable
25; //TTBR0 size
let sctlr_el1 =
(1 << 4) | //Enforce EL0 stack alignment
(1 << 3) | //Enforce EL1 stack alignment
(1 << 1) | // Enforce access alignment
1; //Enable MMU
//0000_0000: nGnRnE device memory
// 0100_0100: non cacheable
let mair = 0b0000_0000_0100_0100;
let mut table = core::slice::from_raw_parts_mut(start as *mut usize, 2048);
for i in 0..(512-8) {
table[i] = (i <<9) |
(1 << 10) | // AF
(0 << 2) | //MAIR index
1; //Block entry
}
for i in (512-8)..512 {
table[i] = (i << 9) |
(1 << 10) | // AF
(1 << 2) | //MAIR index
1; //Block entry
}
table[512] = (512 << 9) |
(1 << 10) | // AF
(1 << 2) | //MAIR index
1; //Block entry
table[1024] = (0x8000000000000000) | start | 3;
table[1025] = (0x8000000000000000) | (start + 512 * 64) | 3;
write!("mair_el1", mair);
write!("ttbr0_el1", start + 1024 * 64);
asm!("isb");
write!("tcr_el1", tcr_el1);
asm!("isb");
write!("sctlr_el1", sctlr_el1);
asm!("isb");
}

How to encode 3 integer values into an uint16_t using bitwise operations?

I want to store 3 unsigned integer values into an uint16_t variable by doing bitwise operations and read them back using bitwise operations. Following is my program to do that:
Code:
#include <iostream>
uint16_t Write(unsigned int iVal1, unsigned int iVal2, unsigned int iVal3) {
// iVal1 should go into the first 8 bits [iVal1 value ranges from 0 to 173]
// iVal2 should go into the 6 bits after that [iVal2 value ranges from 0 to 63]
// iVal3 should go into the 2 bits after that [iVal3 value ranges from 0 to 3]
// Is the below way of writing the bits correct?
return (static_cast<uint16_t>(iVal1)<<8) + (static_cast<uint16_t>(iVal2)<<6) + (static_cast<uint16_t>(iVal3)<<2);
}
unsigned int ReadVal1(const uint16_t theNumber) {
// ival1 is the first 8 bits
uint16_t check1 = 255;
return (theNumber>>8)&check1;
}
unsigned int ReadVal2(const uint16_t theNumber) {
// ival2 is the 6 bits after that
uint16_t check2 = 63;
return (theNumber>>3)&check2;
}
unsigned int ReadVal3(const uint16_t theNumber) {
// ival3 is the last 2 bits
uint16_t check3 = 3;
return (theNumber>>1)&check3;
}
int main() {
std::cout << "Main started" << std::endl;
unsigned int iVal1 = 191;
unsigned int iVal2 = 28;
unsigned int iVal3 = 3;
const uint16_t theNumber = Write(iVal1, iVal2, iVal3);
std::cout << "The first 8 bits contain the number: " << ReadVal1(theNumber) << std::endl;
std::cout << "Then after 6 bits contain the number: " << ReadVal2(theNumber) << std::endl;
std::cout << "Then after 2 bits contain the number: " << ReadVal3(theNumber) << std::endl;
}
In above program following are the ranges of the 3 unsigned integers that need to be encoded.
`iVal1` ranges from `0 to 173`. So its well within 8 bits.
`iVal2` ranges from `0 to 63`. So its well within 6 bits.
`iVal3` ranges from `0 to 3`. So its well within 2 bits.
Question:
I think that the way I am writing the values inside the function Write is wrong. What is the correct way?
Primarily, I am looking for a good explanation of how the encoding using bitwise operation works especially in the context of the goal of my program above.
I believe that my way of reading the values in the functions ReadVal1, ReadVal2 and ReadVal3 is correct. I have figured out the trick of how to read back the values which seems easy. But, I could not well understand the logic of how to encode the values correctly using bitwise operations.
C++ compiler:
I am using a C++11 compiler
The number of bits to shift an integer should not depend on the size of the integer being shifted, but on the size of all the integers that come after it (to the right). Here's some ASCII art to illustrate the principle:
+---+---+---+---+---+---+---+---+
‖i1 |i1 |i1 |i1 |i1 |i1 |i1 |i1 ‖ 8 bit
‖ 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 ‖
+---+---+---+---+---+---+---+---+
_______________________________/
/
| +---+---+---+---+---+---+
| ‖i2 |i2 |i2 |i2 |i2 |i2 ‖ 6 bit
| ‖ 5 | 4 | 3 | 2 | 1 | 0 ‖
| +---+---+---+---+---+---+
| ________/
| /
| |+---+---+
| |‖i3 |i3 ‖ 2 bit
| |‖ 1 | 0 ‖
| |+---+---+
| \ |
|<<(6+2) |<<2 |<<0
v v v
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
‖ F | E | D | C | B | A | 9 | 8 ‖ 7 | 6 | 5 | 4 | 3 | 2 ‖ 1 | 0 ‖
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
‖i1 |i1 |i1 |i1 |i1 |i1 |i1 |i1 ‖i2 |i2 |i2 |i2 |i2 |i2 ‖i3 |i3 ‖
‖ 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 ‖ 5 | 4 | 3 | 2 | 1 | 0 ‖ 1 | 0 ‖
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

Cocos2d-x I don't know how to give animation delay

Now, I did like this. 12 animations move at the same time.
(Sorry, I can't upload Image. So, I did it. |~| is one line and this is 3x4 matrix)
| 1 1 1 |
| 1 1 1 |
| 1 1 1 |
| 1 1 1 |
But, I want like this.
ex) There are 12 pannel foward order upper left corner 1, 2, 3, ... , 12
So, animation moves 1, 2, 3 periods of time, not same time.
| 1 2 3 | // like this.
I did search the internet and added some. But, I couldn't moving that. How can I do them.
Here is my code.
CCSprite* maker_sh = CCSprite::create("img/marker_sh.jpg") ;
CCAnimation* sh_ani = CCAnimation::create() ;
sh_ani -> setDelayPerUnit(0.05) ;
for(int i = 0 ; i < 24 ; i++)
{
int index = i % 5 ;
int rowIndex = i / 5 ;
sh_ani -> addSpriteFrameWithTexture(maker_sh -> getTexture(), CCRectMake(index * 120, rowIndex * 120, 120, 120)) ;
}
CCAnimate* animate[12] ;
CCAction* rep[12] ;
for(int i = 0 ; i < 12 ; i++)
{
animate[i] = CCAnimate::create(sh_ani) ;
rep[i] = CCRepeatForever::create(animate[i]) ;
}
int cnt = 0 ;
CCSprite* test[12] ;
for(int i = 3 ; i > -1 ; i--)
for(int j = 0 ; j < 3 ; j++)
{
cnt++ ;
test[j + (3 - i) * 3] = CCSprite::createWithTexture(maker_sh -> getTexture(), CCRectMake(0, 0, 120, 120)) ;
test[j + (3 - i) * 3] -> setPosition(ccp(j * 125 + 120, i*125 + 75)) ;
this -> addChild(test[j + (3 - i) * 3]) ;
test[j + (3 - i) * 3] -> runAction(rep[j + (3 - i) * 3]) ;
CCLog("%d", cnt) ;
}
Not a smart way,Just hope this will give you some help :)
CCAnimate* animate[12];
CCAction* rep[12];
float interval = 3.f;//set this value that you need
for (int i=0; i<12; i++)
{
CCDelayTime* delay = CCDelayTime::create(i*interval);
animate[i] = CCAnimate::create(sh_ani);
CCAction* action = CCRepeatForever::create(animate[i]) ;
rep[i] = CCSequence::create(delay,action);
}

How does the TED Talk home page organise the grid of videos?

I've been trying to work out exactly how the TED Talk homepage works. Leaving aside all the animation rubbish, I find the way that the boxes are organised is really fascinating.
At first glance it looks like the jQuery masonry plugin, bu it quickly becomes clear that it tends to create several right angle triangle shapes, but has no fixed number of columns or rows, and the final shape produced is always completely solid (no hollow parts).
My initial assumption was that the boxes (their size is predetermined by some factor on the site) were sorted randomly and then sequentially added to the grid using a few simple rules, however I can't identify what those rules might be, or how they could prevent any hollows in the final shape.
Does anyone have any idea how this works?
Could be wrong but a few observations:
Each section has 19 videos
There are 4 sizes 1 (#1), 1/4 (#2), 1/16 (#3) and 1/32 (#4)
For a given section, there are always 4(#1). The number of (#2), (#3) and (#4) can be either:
4(#1), 10(#2), 4(#3), 1(#1) = 19
4(#1), 11(#2), 4(#3), 0(#1) = 19
4(#1), 11(#2), 3(#3), 1(#1) = 19
4(#1), 12(#2), 2(#3), 1(#1) = 19
4(#1), 13(#2), 1(#3), 1(#1) = 19
As for the order:
The first row always contains 2(#1) and 4(#2)
(#4) are always at the bottom of a column
Here is the javascript code which does it (you need a html page with a div#container):
function ted_layout(settings, coordinates_array, num_elements, start_x, start_y, arrangement, remaining_elements, is_child){
var num_columns = arrangement.length;
var col = 0;
var current_x = start_x;
while( col < num_columns){
var column_x_scale = 100 / arrangement[col];
var current_column_arrangement;
if(is_child){
if(num_elements > 14){
if(column_x_scale == 50){
current_column_arrangement = random_shuffle([1, 2, 2]);
} else {
current_column_arrangement = random_shuffle([1, 2]);
}
} else if(num_elements > 10){
if(column_x_scale == 50){
current_column_arrangement = [1];
} else {
current_column_arrangement = random_shuffle([1, 2]);
}
} else{
current_column_arrangement = random_shuffle([1, 2]);
}
} else {
if(num_elements > 14){
if(column_x_scale == 25){
current_column_arrangement = [1, 1];
} else {
current_column_arrangement = [1];
}
} else if(column_x_scale == 25){
current_column_arrangement = [1, 1];
} else {
current_column_arrangement = [1];
}
}
var num_rows = current_column_arrangement.length;
var current_y = start_y;
var row = 0;
while(row < num_rows){
var numRects = current_column_arrangement[row];
var current_rectangle = 0;
var current_rectangle_x = current_x;
while( current_rectangle < numRects){
if(remaining_elements == 0){
return coordinates_array;
}
var currScale = column_x_scale/numRects;
var height = settings.height * currScale*0.01;
var width = settings.width * currScale*0.01;
if(current_rectangle == numRects-1 && row == num_rows-1 && is_child && Math.random() > 0.5){
coordinates_array.push({x: current_rectangle_x, y:current_y, w:width/2, h:height/2, scale:currScale/2*0.01*2})
}
else{
coordinates_array.push({x: current_rectangle_x, y:current_y, w:width, h:height, scale:currScale*0.01*2})
}
current_rectangle_x += width;
remaining_elements--;
current_rectangle++;
}
row++;
current_y += height;
}
current_x = current_rectangle_x;
col++;
}
if( remaining_elements > 0){
coordinates_array = ted_layout(settings, coordinates_array, num_elements, start_x, current_y, random_shuffle([2, 4, 4, 2]), remaining_elements, true);
}
return coordinates_array;
}
function generate_ted_layout(num_elements){
var settings = {
width: 640,
height: 480,
};
var coordinates_array=[];
returned = ted_layout(settings, coordinates_array, num_elements, 0, 0, random_shuffle([2, 4, 4, 2]), num_elements, false);
console.log("Returned", returned)
return returned;
}
function random_shuffle(array){
var temp;
for(var i = array.length - 1; i >= 1; i--){
var elem = Math.floor(Math.random() * (i + 1));
temp = array[elem];
array[elem] = array[i];
array[i] = temp;
}
return array;
}
function initAndLayout() {
var items = generate_ted_layout(20);
var container = $('#container'); // cache jquery object
console.log(items);
for (var i = 0; i < items.length; i++)
{
var item = items[i];
console.log(item);
$('#container').append($('<div class="item"></div>').css({'left': item.x, 'top': item.y, 'width': item.w, 'height': item.h}));
}
}
I think I've worked it out.
First of all the number of items varies substantially, I'm currently viewing a page with only 13 boxes.
To start I'll name each of the 4 sizes of blocks from largest to smallest as:
A,B,C,D
As we know the first 'row' contains two As and two vertical stacks of Bs, for example:
_______________________
| A | B | A | B |
| |___| |___|
| | B | | B |
|_______|___|_______|___|
The arrangement of these appears to be random, but the Bs are always in the same vertical pattern. Looking at this just now I realised that there are only two rows, and the second row works in the same way.
The second row is twice the height of the first, taking up the rest of the page. It is built of horizontally stacked patterns of shapes, which are (at least in part) selected randomly.
I've found 9 of these patterns of shapes, two of which are a single A or B and the rest are:
_______ _______ _______ ___ ___ _______ ___
| B | B | | A | | B | B | |C|C| | B | | A | |C|C|
|___|___| | | |___|___| | B | |___| | |
| A | | | | B | B | |___| |C|D | |
| | |_______| |___|___| |_______|
| | | B | B | | A | | B |
|_______| |___|___| | | |___|
|B |C| |B |C| | |
|___| |___| |_______|
The next question is how are these selected? There may be some clever searching to find the best configuration: for example if there are X items to be displayed we need to find a configuration with a total of X which does not exceed the width of the row.
This could be done with a metric of pattern density, which would be number of blocks divided by the width of the pattern.

Algorithm for finding record with most matching attributes

I'm looking for some algorithm that for a given record with n properties with n possible values each (int, string etc) searches a number of existing records and gives back the one that matches the most properties.
Example:
A = 1
B = 1
C = 1
D = f
A | B | C | D
----+-----+-----+----
1 | 1 | 9 | f <
2 | 3 | 1 | g
3 | 4 | 2 | h
2 | 5 | 8 | j
3 | 6 | 5 | h
The first row would be the one I'm looking for, as it has the most matching values. I think it doesn't need to calculate any closeness to the values, because then row 2 might be more matching.
Loop through each row, add one to the row score of a field matches (field one has a score of 2) and when that's done, you have a resultset of scores which you can sort.
The basic algorithm could look like (in java pseudo code):
int bestMatchIdx = -1;
int currMatches = 0;
int bestMatches = 0;
for ( int row = 0 ; row < numRows ; row++ ) {
currMatches = 0;
for ( int col = 0 ; col < numCols ; col++ ) {
if ( search[col].equals( rows[ row ][ cols] ))
currMatches++;
}
if ( currMatches > bestMatches ) {
bestMatchIdx = row;
bestMatches = currMatches;
}
}
This assumes that you have an equals function to compare, and the data stored in a 2D array. 'search' is the reference row to compare all other rows against it.

Resources